#
# thomas@linuxmuster.net
# 28.02.2015
# GPL v3
#

echo "### 99_start-services postpatch"

# repair permissions for root's scheduled cron jobs
chown root:crontab /var/spool/cron/crontabs/root
chmod 600 /var/spool/cron/crontabs/root

# only if firewall is not custom
if [ "$fwconfig" != "custom" ]; then

 # waiting for firewall to come up 
 c=0
 maxwait=300
 while [ $c -lt $maxwait ]; do

  if ping -c 2 $ipcopip &> /dev/null; then

   # upload root's public key if ipcoppw is set
   if [ -n "$ipcoppw" ]; then

    # upload root's public key
    echo "Uploading root's ssh key to $fwconfig ..."
    mykey="$(cat /root/.ssh/id_dsa.pub)"
    if [ -s /root/.ssh/known_hosts ]; then
     for i in ipfire ipcop "$ipcopip" "$ipcopip_old"; do
      ssh-keygen -f "/root/.ssh/known_hosts" -R ["$i"]:222 &> /dev/null
     done
    fi
    echo "$ipcoppw" | "$SCRIPTSDIR/sshaskpass.sh" ssh -oStrictHostKeyChecking=no -p222 "$ipcopip" "mkdir -p /root/.ssh && echo "$mykey" > /root/.ssh/authorized_keys"

   fi

   success=yes
   break

  fi

  let c+=5
  echo "Waiting for Firewall, $c of $maxwait seconds ..."
  sleep 5

 done

 if [ "$success" != "yes" ]; then
  echo "Fatal! Firewall does not come up!"
 else
  test_pwless_fw
 fi
 
fi # fwconfig

# only if internet connection
if ping -c 2 www.linuxmuster.net &> /dev/null; then
	# set time
	ntpdate pool.ntp.org
	hwclock --utc
fi

# set installed flag
touch $INSTALLED

# reconfigure linuxmuster-pkgs finally
pkgs="base linbo schulkonsole"
[ "$fwconfig" != "custom" ] && pkgs="$pkgs $fwconfig"
for i in $pkgs; do
 dpkg-reconfigure linuxmuster-$i
done

# apply workstation data if internal net has changed
if [ "$1" = "--modify" -a "$internsub" != "$internsub_old" ]; then
 backup_file $WIMPORTDATA
 n=$internsub; o=$internsub_old
 while [ $n -lt $maxsub ]; do
  sed -e "s/;10.$o./;10.$n./g" -i $WIMPORTDATA
  let n+=1
  let o+=1
 done
 rm -f $LINBODIR/*.torrent
 import_printers
fi

# start services not yet started
for i in dbus openbsd-inetd atd cron openntpd linuxmuster-base isc-dhcp-server; do
 service "$i" stop
 service "$i" start
done

# import_workstations
[ "$1" = "--modify" ] && import_workstations

# update linbofs on initial setup or if certificates where renewed
[ "$update_certs" = "yes" -o "$1" = "--first" ] && update-linbofs
