#! /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 curl iotop jnettop python3 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
	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
  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=$(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.sys '@rootfs' $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 [ $? = 0 ]; then
  DoIt
fi
date "+%Y.%m.%d-%H:%M:%S end" >> $LOG
EOS
  chmod u+x /usr/local/bin/local/OnBoot.sh
  echo "@reboot /usr/local/bin/local/OnBoot.sh" >/var/spool/cron/crontabs/root  
fi

