#! /bin/bash
function LogRotate(){
  echo <<EOS >/etc/logrotate.d/local.log.log
/var/log/local/*
{
  missingok
  daily
  copytruncate
  rotate 7
  notifempty
  delaycompress
}
EOS
  echo "created: /etc/logrotate.d/local.log.log"
}

if [ $(id -u) != 0 ]; then
  echo "be root (sudo -s)"
else
  set -x
  apt-get update
  apt-get -y install rsync openssh-server sudo curl iotop jnettop ssl-cert ca-certificates zram-tools htop
  systemctl enable ssh
  systemctl start ssh
  cd /tmp
  echo "= wget"
  wget -q -O /tmp/rsh.tgz https://public.hamatoma.de/rsh.tgz
  wget -q -O /tmp/needed.tgz https://public.hamatoma.de/local_bin_needed.tgz
  wget -q -O /tmp/goodies.tgz https://public.hamatoma.de/local_bin_goodies.tgz
  ls -ld /tmp/needed.tgz /tmp/goodies.tgz
  mkdir -pv /usr/local/bin
  cd /usr/local/bin
  tar xf /tmp/needed.tgz
  echo "= /usr/local/bin populated"
  ln -s local $HOSTNAME 
  ln -sv /usr/local/bin/std.profile /p
  cd /usr/share
  mkdir -p pyrshell
  cd pyrshell
  tar xzf /tmp/rsh.tgz
  cd /usr/share/pyrshell
  PYTHONPATH=/usr/share/pyrshell appl/RestoreTool.py install
  restoretool -v3 init local-bin
  touch /etc/pyrshell/backup.conf
  test -L /p || ln -s /usr/local/bin/std.profile /p
  egrep >/dev/null '^([.]|source) /p$' ~/.bashrc || echo >>~/.bashrc "source /p"
  LogRotate
  echo "= OnBoot"
  mkdir -p /usr/local/bin/local
  cat <<'EOS' >/usr/local/bin/local/OnBoot.sh
#! /bin/bash
set +x
LOG=/var/log/local/onboot.log
LAST=/root/.lastboot
export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin
TODAY=$(date +%Y.%m.%d)
WAIT=300
test "$1" && WAIT=$1

function CheckAgain(){
  RC=0
  local last
  test -e $LAST && last=$(cat $LAST)
  if [ "$last" != $TODAY ]; then
  RC=1
  echo $TODAY >$LAST
  fi
  return $RC
}
function DoIt(){
  #/usr/local/bin/local/SetIp
  echo "$(date +%Y.%m.%d-%H:%M:%S) snapshots" >>$LOG
  #BtrSnapshot daily /media/fs.cave home $LOG
  #BtrSnapshot daily /media/fs.cave opt $LOG
  #BtrSnapshot daily /media/fs.system '@' $LOG
  sleep $WAIT
  apt-get update -qq >/dev/null
  echo "$(date +%Y.%m.%d-%H:%M:%S) upgrade" >>$LOG
  apt-get dist-upgrade -y -qq >/dev/null
}
date "+%Y.%m.%d-%H:%M:%S start" >> $LOG
CheckAgain
if [ $? = 1 ]; then
  DoIt
fi
date "+%Y.%m.%d-%H:%M:%S end" >> $LOG
EOS
  chmod u+x /usr/local/bin/local/OnBoot.sh
  FN=/var/spool/cron/crontabs/root
  if [ -z "$(grep OnBoot $FN)" ]; then
  echo "# minute hour day_of_month month day_of_week command" >>$FN
  echo "# 15/3 * * * * /usr/local/bin/DoIt now" >>$FN
  echo "@reboot /usr/local/bin/local/OnBoot.sh" >>$FN
  fi
fi

