#!/bin/bash


PERM_HOMES=/conf/perm/home
DEFAULT_GROUP=users
CONFDIR=/etc

# Lookup the COMMENT of the ssh-2 key used for authorization (if any)
fingerprint=`cat /var/log/syslog | sed -rn "s/^.*sshd\[$PPID\]: Found matching RSA key: ([0-9:a-f]+).*$/\1/p" | head -n1`
export fingerprint

fname="/tmp/sshkey-login$$.tmp"
grep "^ssh-rsa" /etc/ssh/root-authorized_keys 2> /dev/null | while read key ; do
   echo "$key" > $fname
   if [ `ssh-keygen -l -f $fname | cut -d ' ' -f2` = "$fingerprint" ] ; then
      logger -p security.info -t "LOGIN[$PPID] " "Accepted public key for: `cat $fname | cut -d ' ' -f3-`"
      break
   fi
done
rm -f $fname

function prompt_poweroff() {
   cat << HERE
WARNING: You are about to SHUT DOWN the machine. If this is what you really want,
type "YES" (capital letters, the exact word). If you hit ENTER or type anything
else, the action will be cancelled.

HERE
   read -p "Are you sure to poweroff [YES/*] ? " confirm
   if [ "$confirm" = "YES" ] ; then
	/sbin/poweroff
   else
      echo "CANCELLED."
   fi
}

function modified() {
    grep " $CONFDIR .*rw" /proc/mounts &> /dev/null
}

function reset_dir() {
    xxxx=`pwd`
    cd / ; cd $xxxx
}

function configure() {
    /usr/local/bin/configure $*
    case "$1" in
       start)
        reset_dir;;
       rollback)
        reset_dir;;
       commit)
	reset_dir;;
    esac
}

function rollback() {
    /usr/local/bin/rollback $*
    reset_dir
}

function commit() {
    /usr/local/bin/commit $*
    reset_dir
}

function create_home() {
    base=`dirname $HOME`
    if [ -d "$HOME" ] ; then
	cd $HOME
	return
    fi
    if [ ! -w "$base" ] ; then
	return
    fi
    mkdir $HOME
    if [ -d "$PERM_HOMES/$USER" ] ; then
	cp -a $PERM_HOMES/$USER $base
    fi
    chown $USER.$DEFAULT_GROUP $HOME
    cd $HOME &> /dev/null
}

function elinks_dir() {
    if [ ! -d "$ELINKS_TMP" ] ; then
	mkdir -p $ELINKS_TMP  &> /dev/null
    fi
}

PATH="/sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin"

if [ "$PS1" ]; then
  if [ "$BASH" ]; then
    PS1='\u@\h:\w\$ '
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi

create_home

export ELINKS_TMP=/tmp/elinks-$$
export PATH CONFDIR ELINKS_TMP
export -f reset_dir modified configure rollback commit prompt_poweroff elinks_dir

export PS1="\`{ reset_dir ;  modified ; } && echo -n '`/usr/bin/tput bold`[\u@\h \W]\\$`/usr/bin/tput sgr0`'||echo -n '[\u@\h \W]\\$'\` "
alias ls='ls --color'
alias elinks="elinks_dir ; elinks --config-dir $ELINKS_TMP"
alias links="elinks_dir ; elinks --config-dir $ELINKS_TMP"
alias poweroff='prompt_poweroff'

umask 022
