#!/bin/sh
# 
# VMTux 1.0
#
# /etc/vmt/vmt-start
#
. /etc/vmt/vmt-colors
. /etc/vmt/vmt-conf

PATH=/bin:/sbin

umask 022

BOOTTIME=$(dmesg  | grep 'Run /init' | awk -F "[][]" '{ gsub(/ /,"") ; print $2 }')
verid=$(grep '^VERSION_ID=' /etc/os-release)
VERSION=${verid#*=}
KERNEL="$(uname -r)"
MYNAME=$(grep '^PRETTY_NAME=' /etc/os-release | awk -F\" '{ print $2 }')
CPUMODEL=$(grep "model name" /proc/cpuinfo | tail -1 | awk -F: '{ print $2 }')
TOTALCORES=$(grep -c processor /proc/cpuinfo)
FREQUENCY=$(grep MHz /proc/cpuinfo | tail -1 | awk -F: '{ print $2}')
MEMORY=$(grep MemTotal /proc/meminfo | awk -F: '{ gsub(/ /,""); print $2 }')

echo "\r${BBlue}Booted ${BYellow}${MYNAME}${BGreen} Linux Kernel ${BYellow}$KERNEL${BBlue} in ${BYellow}${BOOTTIME}${BBlue} seconds.${Reset}"
echo "${BBlue}CPU:${BYellow}${CPUMODEL}${BBlue} Cores: ${BYellow}${TOTALCORES}${BBlue} Memory:${BYellow}${MEMORY}${Reset}"

# make some user or use defaultuser

adduser -s /bin/sh -G ${GROUP} -D ${USER}
echo ${USER}:${PASSWORD} | chpasswd -m 2>/dev/null
echo "${USER}\tALL=NOPASSWD: ALL" >> /etc/sudoers 

mkdir -p /home/${USER}

find /etc/skel -type f -exec cp {} /home/${USER} \;
chown -R ${USER}:${GROUP} /home/${USER}
chmod -R g+w,o-rwx /home/${USER}

sync

# wait 5 seconds (max) until a disk is mounted and hyperlinked to vmt data
CNT=0
until [ -h ${VMTDEVICE} ]; do
  [ $((CNT++)) -gt 50 ] && break || usleep 100000
done

if [ $CNT -gt 10 ]; then
  echo "${BBlue}Waited ${BYellow}${CNT}${BBlue} ticks for storage device${Reset}"
fi

if [ ! -h ${VMTDEVICE} ]; then
  STORAGE=$(cat ${FSTAB} | grep "${ADDEDBY}" | grep -v swap | awk '{ print $2 }')
  if [ -n "${STORAGE}" ]; then
    echo "${BBlue}Found persistant storage ${BTellow}${STORAGE}${Reset}"
  else
    STORAGE=/tmp
    echo -n "${BBlue}No storage device found <enter> for options (5 seconds):${Reset} "
    read -t 5
    if [ $? -eq 0 ]; then
      vmt-options
    else
      echo
    fi
  fi
  mkdir -p ${STORAGE}/${VMTNAME}
  ln -s ${STORAGE} ${VMTDEVICE}
fi

mkdir -p ${BACKUP} ${LOOP} ${PKG}
touch ${BOOTLIST}
chown ${USER}:${GROUP} ${BACKUP}
chown root:${GROUP} ${VMT} ${LOOP} ${PKG} ${BOOTLIST}
chmod g+w ${VMT} ${LOOP} ${PKG} ${BOOTLIST}

su - ${USER} -c "/bin/vmt-install -boot"

vmt-backup -r

chown -R root:${GROUP} /opt
chmod -R 775 /opt

if [ -x /opt/startup.sh ]; then
  echo -n "${BBlue}Runnning /opt/startup.sh${Reset} "
  /opt/startup.sh >/tmp/startup.log 2>&1
  echo "${BGreen}done.${Reset}"
fi

exit 0
