#!/bin/sh
# RC Script for Tiny Core Linux
# (c) Robert Shingledecker 2004-2009
# Several modifications for speed by Curaga
. /etc/init.d/tc-functions

USER="tc"
TCEDIR="/tmp/tce/"
TCLOOP="/tmp/tcloop"
MYMENU="/usr/local/tce.menu"
TCEICONS="/usr/local/tce.icons"
TCEINSTALLED="/usr/local/tce.installed"
INSTALLED=""
VERSION="$(cat /usr/share/doc/tc/release.txt)"
DEFAULT_BACKGROUND="#4F5F82"

setupHome(){
   cp -a /etc/skel/. /home/"$USER"/ 2>/dev/null
   busybox bunzip2 -c /usr/share/xpm/logo.xpm.bz2 > /home/"$USER"/.logo.xpm
   sed -i 's/None/'"$DEFAULT_BACKGROUND"'/' /home/"$USER"/.logo.xpm
   chown -Rh "$USER".staff /home/"$USER"
   chmod g+s /home/"$USER"
}

addUser(){
   echo "${GREEN}Adding user ${YELLOW} $USER ${NORMAL}"
   /bin/adduser -s /bin/sh -G staff -D "$USER"
   echo "$USER":tcuser | /usr/sbin/chpasswd
   echo -e "$USER\tALL=NOPASSWD: ALL" >> /etc/sudoers
   setupHome
}

### END functions

# Main
echo -n "${GREEN}Booting ${YELLOW}"
cat /usr/share/doc/tc/release.txt
echo -n "${NORMAL}"

# Mount /proc.
[ -f /proc/cmdline ] || /bin/mount /proc

# Remount rootfs rw.
/bin/mount -o remount,rw /

# Mount system devices from /etc/fstab.
/bin/mount -a

KERNEL="$(uname -r)"
echo "${GREEN}Running Linux Kernel ${YELLOW}$KERNEL${GREEN}.${NORMAL}"
export PATH=/usr/local/sbin:/usr/local/bin:"$PATH"

# Start Udev to populate /dev and handle hotplug events
echo -n "${BLUE}Starting udev daemon for hotplug support...${NORMAL}"
/sbin/udevd --daemon 2>/dev/null >/dev/null
/sbin/udevtrigger 2>/dev/null >/dev/null &
rotdash $!
#echo "/sbin/udevd" > /proc/sys/kernel/hotplug
echo "${GREEN}Done.${NORMAL}"

# Here we check all the boot parameters using the fastest way known to men, case & loop
echo -n "${BLUE}Checking boot options...${NORMAL}"
for i in `cat /proc/cmdline`; do
  case $i in
    *=*)
    	  case $i in
    	   waitusb*) WAITUSB=${i#*=} ;;
    	   lang*) LANGUAGE=${i#*=} ;;
    	   kmap*) KEYMAP=${i#*=} ;;
    	   tz*) TZ=${i#*=} ;;
    	   desktop*) DESKTOP=${i#*=} ;;
    	   user*) USER=${i#*=} ;;
    	   home*) MYHOME=${i#*=} ;;
    	   cryptohome*) CRYPTOHOME=${i#*=} ;;
    	   tcvd*) TCVD=${i#*=} ;;
    	   opt*) MYOPT=${i#*=} ;;
    	   local*) LOCAL=${i#*=} ;;
    	   swapfile*) SWAPFILE=${i#*=} ;;
    	   resume*) RESUME=${i#*=} ;;
  	   host*) HOST=1 ;;
    	   settime*) SETTIME=${i#*=} ;;
    	   thm*) THEME=${i#*=} ;;
    	   bkg*) BACKGROUND=${i#*=} ;;
           nfsmount* ) NFSMOUNT=${i#*=} ;;
           tftplist* ) TFTPLIST=${i#*=} ;;
    	  esac
      ;;
      *)
	  case $i in
	   nofstab) NOFSTAB=1 ;;
	   syslog) SYSLOG=1 ;;
	   noutc) NOUTC=1 ;;
	   nodhcp) NODHCP=1 ;;
	   noicons) NOICONS=1 ;;
	   text) TEXT=1 ;;
	   superuser) SUPERUSER=1 ;;
	   noswap) NOSWAP=1 ;;
	   secure) SECURE=1 ;;
	   protect) PROTECT=1 ;;
	   ssh) SSH=1 ;;
	   cron) CRON=1 ;;
	   xsetup) XSETUP=1 ;;
	   laptop) LAPTOP=1 ;;
	   base) ONLYBASE=1 ;;
	   showapps) SHOWAPPS=1 ;;
	   norestore) NORESTORE=1 ;;
	   noautologin) NOAUTOLOGIN=1 ;;
	   pause) PAUSE=1 ;;
	  esac
      ;;
  esac
done
echo "${GREEN}Done.${NORMAL}"

[ -n "$WAITUSB" ] && sleep "$WAITUSB"
modprobe scsi_wait_scan 2>/dev/null
#modprobe ohci_hcd

if [ -n "$NOFSTAB" ]; then
  echo "${BLUE}Skipping /etc/fstab creation as requested from the boot command line.${NORMAL}"
else
  echo "${BLUE}Scanning hard disk partitions to create ${YELLOW}/etc/fstab ${NORMAL}"
  /usr/sbin/rebuildfstab & fstab_pid=$!
  mv /tmp/98-tc.rules /etc/udev/rules.d/. 2>/dev/null
  /sbin/udevcontrol reload_rules &
fi

if [ -n "$SYSLOG" ]; then
   /sbin/syslogd && echo "${GREEN}syslog started.${NORMAL}"
   /sbin/klogd && echo "${GREEN}klog started."
fi

[ -n "$LANGUAGE" ] || LANGUAGE="C"
echo -n "${GREEN}Setting Language to ${MAGENTA}$LANGUAGE"
echo "LANG=$LANGUAGE" > /etc/sysconfig/language
echo "${GREEN} Done.${NORMAL}"

[ -n "$TZ" ] || TZ="UTC"
echo -n "${GREEN}Setting Timezone to ${MAGENTA}$TZ"
echo "TZ=$TZ" > /etc/sysconfig/timezone
echo "${GREEN} Done.${NORMAL}"

if [ -n "$NOUTC" ]; then
   hwclock -l -s &
else
   hwclock -u -s &
fi

if [ -n "$HOST" ]; then
   sethostname
else
   /bin/hostname -F /etc/hostname
fi

/sbin/ifconfig lo 127.0.0.1 up
/sbin/route add 127.0.0.1 lo &

# dhcp.sh runs udhcpc async, so it exits before network is up
wait4Server() {
   [ -z "$DHCP_RAN" ] && /etc/init.d/dhcp.sh
   CNT=0
   until ping -c 1 $1 >/dev/null 2>&1
   do
      [ $((CNT++)) -gt 30 ] && break || sleep 1
   done
   DHCP_RAN=1
}

# First process tftp entries
modprobe -q squashfs 2>/dev/null
if [ -n "$TFTPLIST" ]; then
   SERVER=`echo $TFTPLIST | awk -F\: '{ print $1 }'`
   FILE=`echo $TFTPLIST | awk -F\: '{ print $2 }'`
   wait4Server $SERVER
   (  TMPDIR=/tmp/tftp
      TCEDIR=/opt/.tce_dir
      echo > $TCEDIR
      mkdir $TMPDIR ; cd $TMPDIR
      NAME=${FILE##*/}
      tftp -g -r $FILE $SERVER
      [ $SHOWAPPS ] && echo -ne "${BLUE}TFTP Loading Extensions ${YELLOW}"
      while read EXTENSION
      do
         tftp -g -r $EXTENSION $SERVER
         EXTNAME=${EXTENSION##*/}
         [ $SHOWAPPS ] && echo -ne "$EXTNAME "
         /usr/bin/tce-load -i $TMPDIR/$EXTNAME
      done < $NAME
      [ $SHOWAPPS ] && echo "${GREEN} Done.${NORMAL}"
      rm $NAME $TCEDIR
   )
fi

if [ -n "$NFSMOUNT" ]; then
   SERVER=`echo $NFSMOUNT | awk -F\: '{ print $1 }'`
   wait4Server $SERVER
   echo "$NFSMOUNT /mnt/nfs nfs defaults,nolock 0 0" >> /etc/fstab
   [ $SHOWAPPS ] && echo "Mounting $NFSMOUNT"
   mkdir /mnt/nfs
   mount /mnt/nfs >/dev/null 2>&1
fi

if grep -q "^/dev/root" /proc/mounts; then
   INSTALLED=1
   echo "${RED}Detected Traditional (Scatter) Hard drive installation.${NORMAL}"
fi

EDITION=`cat /usr/share/doc/tc/release.txt|cut -f1 -d_`
# The default Xserver for tinycore is Xvesa. Other X should overwrite.
if [ "$EDITION" == "tinycore" ]; then 
  echo "Xvesa" > /etc/sysconfig/Xserver
  /sbin/ldconfig 2>/dev/null
fi  

[ -n "$TEXT" ] && touch /etc/sysconfig/text

if [ -n "$LOCAL" ]; then
   wait $fstab_pid
   LOCAL_DEVICE="${LOCAL%%/*}"
   mount /mnt/"$LOCAL_DEVICE" -o suid
   if [ "$?" == 0 ]; then
      [ -d /mnt/"$LOCAL_DEVICE"/tclocal ] && mount --bind /mnt/"$LOCAL_DEVICE"/tclocal /usr/local/ && LOCAL_READY=1
      [ -z "$LOCAL_READY" ] &&  [ -f /mnt/"$LOCAL_DEVICE"/tclocal ] && mount -o loop,suid /mnt/"$LOCAL_DEVICE"/tclocal /usr/local/ && LOCAL_READY=1
      [ -z "$LOCAL_READY" ] &&  mkdir /mnt/"$LOCAL_DEVICE"/tclocal && mount --bind /mnt/"$LOCAL_DEVICE"/tclocal /usr/local/
   fi
   # Final test for /usr/local mount and call setup routines for libraries, modules, and menu.
   if grep -q \/usr\/local /etc/mtab; then
     /sbin/ldconfig 2>/dev/null
     /sbin/depmod -a 2>/dev/null
     /sbin/udevtrigger
   fi
fi
#

if [ -n "$USER" ]; then
   if ! grep "$USER" /etc/passwd >/dev/null; then addUser; fi
else
   USER="tc"
fi
echo "$USER" > /etc/sysconfig/tcuser
if [ -n "$SUPERUSER" ]; then
   touch /etc/sysconfig/superuser
else
   sed -i 's/root/'"$USER"'/' /etc/inittab 
#  kill -SIGHUP 1
#  sync
fi
mkdir -p /home/"$USER"
    	   
#Check for Virtual Hard Drive
if [ -n "$TCVD" ]; then
  wait $fstab_pid
  TCVD="${TCVD#/}"
  TCVD="${TCVD#dev/}"
  TCVD_DEVICE="${TCVD%%/*}"
  TCVD_LOOPFILE="${TCVD#*/}"
  if [ "$TCVD_DEVICE" == "$TCVD_LOOPFILE" ]; then
    TCVD_DEVICE="$(autoscan $TCVD_LOOPFILE 'f')"
  fi   
  PARTITION="${TCVD_DEVICE##/dev/}"
  find_mountpoint "$PARTITION"
  if [ -n "$MOUNTPOINT" ]; then
     [ "$MOUNTED" == "yes" ] || /bin/mount "$MOUNTPOINT"
     usleep_progress
     if [ -f "$MOUNTPOINT"/"$TCVD_LOOPFILE" ]; then
       [ -d /mnt/tcvd ] || /bin/mkdir /mnt/tcvd
       ln -sf "$MOUNTPOINT"/"$TCVD_LOOPFILE" /dev/tcvd
       printf "/dev/tcvd \t/mnt/tcvd \text2\tloop\t0 0 #Added by TC\n" >> /etc/fstab
       sync
     fi
  fi
fi  

unset HOME_SETUP  # Used by both CRYPTOHOME and persistent HOME
if [ -n "$CRYPTOHOME" ]; then
   TCHOME="tchome.aes"
   wait $fstab_pid
   PARTITION=${CRYPTOHOME##/dev/}
   find_mountpoint "$PARTITION"
   if [ -n "$MOUNTPOINT" ]; then
      [ "$MOUNTED" == "yes" ] || mount "$MOUNTPOINT"
      if [ -f "$MOUNTPOINT/$TCHOME" ]; then
         echo "${GREEN}Mounting encrypted tchome file on /mnt/"$MYHOME" as /home/tc.${NORMAL}"
         echo "${GREEN}Please enter your encrypted home password..${NORMAL}"
         mount "$MOUNTPOINT/$TCHOME" /home/"$USER" -oencryption=AES
         if [ "$?" == 0 ]; then HOME_SETUP=1; fi
      fi
   else
      echo "Device not found! Ignoring persistent CRYPTOHOME request!"
   fi
fi

if [ -n "$MYHOME" ]; then
   wait $fstab_pid
   PARTITION=${MYHOME##/dev/}
   find_mountpoint "$PARTITION"
   if [ -n "$MOUNTPOINT" ]; then
      [ "$MOUNTED" == "yes" ] || mount "$MOUNTPOINT"
      if [ -d "$MOUNTPOINT/home/$USER" ]; then
         mount --bind "$MOUNTPOINT/home" /home
         HOME_SETUP=1
      else
         mkdir -p "$MOUNTPOINT/home/$USER"
         mount --bind "$MOUNTPOINT/home" /home
      fi
   else
      echo "Device not found! Ignoring persistent HOME request!"
   fi
fi

[ ! "$HOME_SETUP" ] && setupHome

unset OPT_SETUP
if [ -n "$MYOPT" ]; then
   wait $fstab_pid
   PARTITION=${MYOPT##/dev/}
   find_mountpoint "$PARTITION"
   if [ -n "$MOUNTPOINT" ]; then
      [ "$MOUNTED" == "yes" ] || mount "$MOUNTPOINT"
      [ -d "$MOUNTPOINT"/opt ] || mkdir "$MOUNTPOINT"/opt
      yes n | cp -ai /opt/. "$MOUNTPOINT"/opt/ 2>/dev/null
      mount --bind "$MOUNTPOINT"/opt/ /opt/
      chgrp -R staff /opt/ >/dev/null 2>&1
      chmod -R g+w /opt/ >/dev/null 2>&1
      chmod g+s /opt/ >/dev/null 2>&1
   else
      "Echo invalid device specified. Skipping persistent opt request!"
   fi
fi


[ -n "$XSETUP" ] && touch /tmp/xsetup_requested

if [ -n "$LAPTOP" ]; then
   modprobe ac && modprobe battery 2>/dev/null
   modprobe yenta_socket >/dev/null 2>&1 || modprobe i82365 >/dev/null 2>&1
   /sbin/udevtrigger 2>/dev/null >/dev/null &
   echo " ${GREEN}Laptop options enabled (AC,Battery, & PCMCIA).${NORMAL}"
fi

if [ -n "$NOSWAP" ]; then
   echo "${BLUE}Ignoring swap partition(s) seek as requested.${NORMAL}"
else
   wait $fstab_pid
   /sbin/swapon -a
   if [ "$?" == 0 ]; then echo "${GREEN}Possible swap partition(s) enabled.${NORMAL}"; fi
fi

if [ -n "$SWAPFILE" ]; then
   wait $fstab_pid
   SWAPFILE=${SWAPFILE##/dev/}
   find_mountpoint "$SWAPFILE"
   if [ -n "$MOUNTPOINT" ]; then
      if [ "$MOUNTED" == "yes" ]; then
         swapon "$MOUNTPOINT"/tc.swp
      else
         mount "$MOUNTPOINT" && swapon "$MOUNTPOINT"/tc.swp
      fi
   fi
fi

if [ -n "$RESUME" ]; then
  rm -f /etc/sysconfig/tc.resume 2>/dev/null
  RESUME=`basename $RESUME`
  SWAP_SIZE=$(cat /proc/swaps | grep "$RESUME" | awk '{print $3}')
  [ -z "$SWAP_SIZE" ] && /sbin/swapon /dev/"$RESUME" &&  SWAP_SIZE=$(cat /proc/swaps | grep "$RESUME" | awk '{print $3}')
  [ -z "$SWAP_SIZE" ] && exit 1
  MEM_SIZE=$(cat /proc/meminfo | awk '/MemTotal/{print $2}')
  if [ $SWAP_SIZE -gt $MEM_SIZE ]; then
    grep -q disk /sys/power/state &&  echo "disk" > /etc/sysconfig/tc.resume
  fi
fi

if [ -n "$SECURE" ]; then
   getpasswd "root"
   echo "root:$PASSWD" | chpasswd
   getpasswd "$USER"
   echo "$USER:$PASSWD" | chpasswd
fi
if [ -n "$PROTECT" ]; then
   getpasswd "encryption"
   echo "$PASSWD" > /etc/sysconfig/bfe
fi

# Setup base directories for TCE Applicatons
[ -d "$TCEINSTALLED" ] || mkdir "$TCEINSTALLED"
[ -d "$TCEDIR" ] || mkdir "$TCEDIR"
[ -d "$MYMENU" ] || mkdir "$MYMENU"
[ -d "$TCEICONS" ] || mkdir "$TCEICONS"
[ -d "$TCLOOP" ] || mkdir "$TCLOOP"
echo "$TCEDIR" > /opt/.tce_dir
chgrp staff "$TCEDIR" "$TCEINSTALLED" "$MYMENU" "$TCEICONS" "$TCLOOP" "/opt/.tce_dir"
chmod g+w "$TCEDIR" "$TCEINSTALLED" "$MYMENU" "$TCEICONS" "$TCLOOP" "/opt/.tce_dir"
sync

if [ -n "$ONLYBASE" ]; then
   echo "${GREEN}Skipping TCE Application Extensions as requested on the command line.${NORMAL}"
else
   wait $fstab_pid
   MSSG="${BLUE}Loading Tiny Core Applications Extensions...${NORMAL}"
   if [ -n "$SHOWAPPS" ]; then
     touch /etc/sysconfig/showapps
     echo "$MSSG"
     /usr/bin/tce-setup "booting" 
     echo "${GREEN}Done.${NORMAL}"
   else
     echo -n "$MSSG"
     /usr/bin/tce-setup "booting" > /dev/null 2>&1 &
     rotdash $!
     echo "${GREEN}Done.${NORMAL}"
     if [ -s /tmp/aberr ]; then
       echo "${RED}Warning! Errors occured during the loading of the extensions.${YELLOW}"
       cat /tmp/aberr
       echo -n "${RED}Press Enter key.${NORMAL}"; read ans
     fi
   fi
fi

# If desktop is specified use that
if [ -n "$DESKTOP" ]; then
  echo "$DESKTOP" > /etc/sysconfig/desktop
else
  [ -s /etc/sysconfig/desktop ] && DESKTOP=`cat /etc/sysconfig/desktop`
fi
[ -n "$THEME" ] && echo "$THEME"  > /etc/sysconfig/theme
[ -n "$BACKGROUND" ] && echo "$BACKGROUND" > /etc/sysconfig/background

# If restore then also pass TCE directory for quick look of mydata.tgz backupfile
if [ -n "$NORESTORE" ]; then
  echo "${GREEN}Skipping restore as requested from the command line.${NORMAL}"
else
  TCEDIR=`cat /opt/.tce_dir`
  /etc/init.d/tc-restore.sh "$TCEDIR"
fi

# After restore items
if [ -n "$NODHCP" ]; then
  echo "${GREEN}Skipping DHCP broadcast/network detection as requested on boot commandline.${NORMAL}"
else
  [ -z "$DHCP_RAN" ] && /etc/init.d/dhcp.sh &
fi

[ -n "$KEYMAP" ] || KEYMAP="us"
if [ -f "/usr/share/kmap/$KEYMAP.kmap" ]; then
   echo -n "${GREEN}Setting keymap to ${MAGENTA}$KEYMAP"
   /sbin/loadkmap < /usr/share/kmap/$KEYMAP.kmap
   echo "KEYMAP=$KEYMAP" > /etc/sysconfig/keymap
   echo "${GREEN} Done.${NORMAL}"
fi

[ -n "$CRON" ] && /etc/init.d/crond start
[ -n "$SSH" ] && /etc/init.d/dropbear start >/dev/null && echo " ${GREEN}ssh started.${NORMAL}"
[ -n "$SETTIME" ] && /usr/bin/getTime.sh

ICONS="wbar"
if [ -n "$NOICONS" ] || [ ! -f /usr/share/wbar/dot.wbar ]; then
   unset ICONS
fi
[ "${#ICONS}" == 0 ] || echo "$ICONS" > /etc/sysconfig/icons

/opt/bootlocal.sh &

[ -n "$NOAUTOLOGIN" ] && touch /etc/sysconfig/noautologin

if [ -n "$PAUSE" ]; then
   echo -n "${BLUE}Boot time configuration completed. Press <Enter> to continue.${NORMAL}"
   read junk
fi
