#!/bin/bash

# This script is sourced both by .bash_profile and .xsession-local and can
# thus be used for initialization duties that need to be done when
# logging in on a console, via ssh, or at the start of an X session.

# pull in proxy settings

cd ~

for file in /etc/use-proxy ~/.use-proxy; do
	if [ -x "$file" ]; then
		. "$file"
	fi
done

# set package parameters

export DEBFULLNAME="Marc Haber"
export DEBEMAIL="mh+debian-packages@zugschlus.de"

export CVS_RSH=ssh

export ALIOTHUSER=zugschlus

# editor

if [ -x "$(which vi)" ]; then
  EDITOR="$(which vi)"
  VISUAL="$EDITOR"
  CHANGESEDITOR="$EDITOR"
fi

if [ -x "$(which jed)" ]; then
  EDITOR="$(which jed)"
  VISUAL="$EDITOR"
  CHANGESEDITOR="$EDITOR"
fi
export EDITOR VISUAL CHANGESEDITOR

# pull active network scheme to environment

if [ -e "/etc/network/schemes/active" ]; then
  NW_SCHEME="$(cat /etc/network/schemes/active)"
else
  #echo >&2 "WARN: no active network scheme found, assuming \"default\""
  NW_SCHEME="default"
fi

# build authorized_keys

LOC_UMASK="$(umask)"
umask 022
if [ -f ".ssh/authorized_keys.conf" ]; then
  . .ssh/authorized_keys.conf
  AKTMP=".ssh/authorized_keys.tmp"
  > "$AKTMP"
  for class in $AKC_CLASSES; do
    if ! cat $(find .ssh/authorized_keys.d/$class -type f -print) >> "$AKTMP"; then
      echo >&2 "ERR: cannot make new authorized_keys, filesytem full?"
      rm -f "$AKTMP"
      break
    fi
  done
  if [ -f "$AKTMP" ]; then
    mv "$AKTMP" .ssh/authorized_keys
  fi
  unset AKC_CLASSES
  unset AKTMP
  unset class
else
  echo >&2 "WARN: no .ssh/authorized_keys.conf found, not touching authorized_keys"
fi

# build ssh config

if [ -f ".ssh/config.conf" ]; then
  . .ssh/config.conf
  CTMP=".ssh/config.tmp"
  > "$CTMP"
  for class in $C_CLASSES; do
    if [ -d ".ssh/config.d/$class" ]; then
      if ! cat $(find .ssh/config.d/$class -maxdepth 1 -type f -print) >> "$CTMP"; then
        echo >&2 "ERR: cannot make new config, filesytem full?"
        rm -f "$CTMP"
        break
      fi
      if [ -d ".ssh/config.d/$class/$NW_SCHEME" ]; then
        if ! cat $(find .ssh/config.d/$class/$NW_SCHEME -maxdepth 1 -type f -print) >> "$CTMP"; then
          echo >&2 "ERR: cannot make new config, filesytem full?"
          rm -f "$CTMP"
          break
        fi
      fi
    else
      echo >&2 "WARN: No directory ~/.ssh/config.d/$class"
    fi
  done
  if [ -f "$CTMP" ]; then
    mv "$CTMP" .ssh/config
  fi
  unset C_CLASSES
  unset CTMP
  unset class
else
  if [ -f .ssh/config ] || [ -h .ssh/config ]; then
    rm -f .ssh/config
  fi
fi

umask $LOC_UMASK
unset LOC_UMASK

unset RET RET1 RET2 FILELIST

