#!/bin/sh
# Author: Blake, Kuo-Lien Huang
# License: GPL
# Description:
#   setup user's krdc 
#

id=`id -u`
if [ "$id" != "0" ]; then
  echo "You must be root to use this script"
  echo "Use sudo to enable it for users"
  exit 1
fi

drblroot="/var/lib/diskless/default"

resshkeygen=0
if [ ! -f /root/.ssh/id_rsa ]; then
  tail +${LINENO} $0 > autosshkeygen
  chmod 755 autosshkeygen
  ./autosshkeygen $USER
  mv /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys
  rm -f autosshkeygen
  resshkeygen=1
fi

for host in `ls $drblroot`
do
  if [ "$host" = "." -o "$host" = ".." -o "$host" = "root" ]; then
    continue
  fi
  if [ $resshkeygen -eq 1 -o ! -f $drblroot/$host/root/.ssh/id_rsa ]; then
    mkdir -p $drblroot/$host/root/.ssh
    cp /root/.ssh/id_rsa $drblroot/$host/root/.ssh/id_rsa
    cp /root/.ssh/authorized_keys $drblroot/$host/root/.ssh/authorized_keys
  fi
done

# krdc.sh
cat <<-EOF > krdc.sh
#!/bin/sh
host=\$(/sbin/route -n | grep -e "^0.0.0.0" | awk '{print \$2}')
xuser=\$(who | awk '{print \$1" "\$2}' | grep ":0" | cut -d" " -f1)
if [ "\$xuser" != "" -a "\$host" != "" ]; then
  cat <<-CONFIG > /home/\$xuser/.kde/share/config/krdcrc
browsingPanel=false
serverHistory=\$host:0
CONFIG
fi
#rm -f krdc.sh
EOF
chmod 755 krdc.sh

# execute the command
for host in `ls $drblroot`
do
  if [ "$host" = "." -o "$host" = ".." -o "$host" = "root" ]; then
    continue
  fi
  # check if $host is myself
  me=`/sbin/ifconfig | grep "$host" | cut -d: -f2 | cut -d' ' -f1`
  if [ "$me" = "" -o "$me" != "$host" ]; then
    echo "=== $host ==="
    if /bin/ping -c 2 $host > /dev/null 2>&1; then
      scp -o StrictHostKeyChecking=no krdc.sh root@$host:~
      ssh -o StrictHostKeyChecking=no root@$host ./krdc.sh 
    else
      echo "$host is unreachable.." 
    fi
  fi
done

# krdc.sh
rm -f krdc.sh
exit 0
