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

USER="tc"
TCEDIR="/tmp/tce"
TCLOOP="/tmp/tcloop"
TCEINSTALLED="/usr/local/tce.installed"
INSTALLED=""
VERSION="$(cat /usr/share/doc/tc/release.txt)"

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

### END functions

# Main
clear
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"

# 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#*=} ;;
    	   icons*) ICONS=${i#*=} ;;
    	   user*) USER=${i#*=} ;;
    	   home*) MYHOME=${i#*=} ;;
    	   tcvd*) TCVD=${i#*=} ;;
    	   opt*) MYOPT=${i#*=} ;;
    	   local*) LOCAL=${i#*=} ;;
    	   swapfile*) SWAPFILE=${i#*=} ;;
    	   resume*) RESUME=${i#*=} ;;
  	   host*) HOST=1 ;;
           nfsmount* ) NFSMOUNT=${i#*=} ;;
           tftplist* ) TFTPLIST=${i#*=} ;;
           httplist* ) HTTPLIST=${i#*=} ;;
           aoe* ) AOE=${i#*=} ;;
           mydata* ) MYDATA=${i#*=} ;;
           xvesa* ) XVESA=${i#*=} ;;
           blacklist* ) BLACKLIST="$BLACKLIST ${i#*=}" ;;
    	  esac
      ;;
      *)
	  case $i in
	   nozswap) NOZSWAP=1 ;;
	   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 ;;
	   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}"

if [ -n "$BLACKLIST" ]; then
  mkdir -p /etc/modprobe.d
  for i in $BLACKLIST; do
    echo "blacklist $i" >> /etc/modprobe.d/blacklist.conf
  done
fi

# 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/udevadm trigger 2>/dev/null >/dev/null &
rotdash $!
echo "${GREEN}Done.${NORMAL}"

[ -n "$WAITUSB" ] && (
  case $WAITUSB in
    *:*) dev=${WAITUSB#*:}
    timeout=$((${WAITUSB%:*} * 4))
    while [ $timeout -gt 0 ]; do
      echo -en "${BLUE}\rWaiting as requested ... ${NORMAL}$(($timeout / 4)) "
      timeout=$(($timeout - 1))
      sleep 0.25
      blkid -lt $dev >/dev/null && timeout=0
    done
    echo
    ;;
    *) sleep "$WAITUSB" ;;
  esac
)

modprobe loop 2>/dev/null
#modprobe ohci_hcd

if [ -n "$NOZSWAP" ]; then
  echo "${BLUE}Skipping compressed swap in ram as requested from the boot command line.${NORMAL}"
else
  modprobe -q ramzswap
  rzscontrol /dev/ramzswap0 --init # Defaults to max 25% of ram.
  swapon /dev/ramzswap0
  echo "/dev/ramzswap0  swap         swap    defaults,noauto   0       0" >> /etc/fstab # Lets swapoff -a work
fi

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}"
  modprobe scsi_wait_scan 2>/dev/null
  /usr/sbin/rebuildfstab & fstab_pid=$!
  mv /tmp/98-tc.rules /etc/udev/rules.d/. 2>/dev/null
  /sbin/udevadm control --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"
export TZ
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 &

if [ -n "$AOE" ]; then
   IFACE=$( echo $AOE | awk -F: '{ print $1 }')
   DEV=$( echo $AOE | awk -F: '{ print $2 }')
   ifconfig $IFACE up
   modprobe aoe
   echo "${BLUE}Waiting for $DEV${NORMAL}"
   CNT=120
   until [ -e /dev/etherd/interfaces ]
   do
      [ $((--CNT)) -le 0 ] && break
      echo -ne "${RED}$CNT  \r"
      sleep 1
   done
   printf "%s\0" $IFACE > /dev/etherd/interfaces
   echo > /dev/etherd/discover
   until [ -e /dev/etherd/$DEV ]
   do
      [ $((--CNT)) -le 0 ] && break
      echo -ne "${RED}$CNT  \r"
      sleep 1
   done
   if [ $CNT -gt 0 ] ; then
      ln -s /dev/etherd/$DEV /dev/$DEV
      mkdir -p /mnt/$DEV
      mount /dev/$DEV /mnt/$DEV >/dev/null 2>&1
   else
      echo -ne "\n$DEV NOT mounted! Press <ENTER>" ; read junk
   fi
   echo "${NORMAL}"
fi

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

get_app() {
   PROTO=$1
   HOST=${2%%/*}
   REST=${2#*/}
   LENG=$((${#HOST}-1)) ; LAST=${HOST:$LENG:1}
   [ "$LAST" == ":" ] && HOST=${HOST:0:$LENG}
   FILE=${REST%:*}
   NAME=${FILE##*/}
   OPTS=${REST#*:}
   [ "$OPTS" == "no-ping" ] && NOPING=1 || NOPING=0

   [ -z "$DHCP_RAN" ] && wait4Server $HOST $NOPING
   (  TCE=/opt/tce; OPT=$TCE/optional; ONBOOT=$TCE/onboot.lst 
      mkdir -p $OPT 2>/dev/null ; cd $OPT
      [ "$PROTO" = "TFTP" ] && tftp -g -r $FILE $HOST
      [ "$PROTO" = "HTTP" ] && wget -q http://${HOST}/${FILE}
      [ $SHOWAPPS ] && echo -ne "${BLUE}TFTP Loading Extensions ${YELLOW}"
      dos2unix -u $NAME
      while read FILE
      do
         APP=${FILE##*/}
         [ "$PROTO" = "TFTP" ] && tftp -g -r $FILE $HOST
         [ "$PROTO" = "HTTP" ] && wget -q http://${HOST}/${FILE}
         [ $SHOWAPPS ] && echo -ne "$APP "
         echo "$APP" >> $ONBOOT
      done < $NAME
      [ $SHOWAPPS ] && echo "${GREEN} Done.${NORMAL}"
      rm $NAME
   )
}

# First process tftp and http entries
modprobe -q squashfs 2>/dev/null
[ -n "$TFTPLIST" ] && get_app "TFTP" $TFTPLIST
[ -n "$HTTPLIST" ] && get_app "HTTP" $HTTPLIST

if [ -n "$NFSMOUNT" ]; then
   SERVER=$( echo $NFSMOUNT | awk -F: '{ print $1 }')
   DIR=$(    echo $NFSMOUNT | awk -F: '{ print $2 }')
   OPTS=$(   echo $NFSMOUNT | awk -F: '{ print $3 }')
   [ -z "$DHCP_RAN" ] && wait4Server $SERVER $OPTS
   wait $fstab_pid
   echo "${SERVER}:${DIR} /mnt/nfs nfs defaults,nolock 0 0" >> /etc/fstab
   [ $SHOWAPPS ] && echo "Mounting ${SERVER}:${DIR}"
   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/udevadm trigger
   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
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
if [ -n "$MYHOME" ]; then
   wait $fstab_pid
   PARTITION=${MYHOME##/dev/}
   find_mountpoint "$PARTITION"
   if [ -n "$MOUNTPOINT" ]; then
      [ "$MOUNTED" == "yes" ] || mount "$MOUNTPOINT"

      MS_MNTS=`mount|awk '$5~/fat|vfat|msdos|ntfs/{printf "%s ",$3}'`
      case "$MS_MNTS" in 
         *"$MOUNTPOINT"* )
           echo "Persistent HOME not supported on Microsoft File Systems."
           echo "${YELLOW}Request for persistent HOME on $PARTITION ignored."
           echo -n "${RED}Press Enter key.${NORMAL}"; read ans
         ;;
         * )
           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
         ;;
      esac

   else
      echo "Invalid device specified. 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"

      MS_MNTS=`mount|awk '$5~/fat|vfat|msdos|ntfs/{printf "%s ",$3}'`
      case "$MS_MNTS" in 
         *"$MOUNTPOINT"* )
           echo "Persistent OPT not supported on Microsoft File Systems."
           echo "${YELLOW}Request for persistent OPT on $PARTITION ignored."
           echo -n "${RED}Press Enter key.${NORMAL}"; read ans
         ;;
         * )
           [ -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
         ;;
      esac

   else
      echo "Invalid device specified. Skipping persistent OPT request!"
   fi
fi

[ -n "$XVESA" ]  && sed -i 's/1024x768x32/'"$XVESA"'/' /home/"$USER"/.xsession
[ -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/udevadm trigger 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 2>/dev/null
   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

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

chmod u+s /bin/busybox /usr/bin/sudo

if [ "$NOICONS" == 1 ]; then
  > /etc/sysconfig/icons
else  
# If icon manager is specified use that
  if [ -n "$ICONS" ]; then
    echo "$ICONS" > /etc/sysconfig/icons
  else
    [ -s /etc/sysconfig/icons ] && ICONS=`cat /etc/sysconfig/icons`
  fi
fi  
sync

if [ -n "$ONLYBASE" ]; then
   echo "${GREEN}Skipping TCE Extensions as requested on the command line.${NORMAL}"
else
   wait $fstab_pid
   MSSG="${BLUE}Loading Extensions...${NORMAL}"
   if [ -n "$SHOWAPPS" ]; then
     touch /etc/sysconfig/showapps
     echo "$MSSG"
     /usr/bin/tce-setup "booting" 
     rm /etc/sysconfig/showapps
     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

[ -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

if [ -n "$SECURE" ]; then
   getpasswd "root"
   echo "root:$PASSWD" | chpasswd -m
   getpasswd "$USER"
   echo "$USER:$PASSWD" | chpasswd -m
fi
if [ -n "$PROTECT" ]; then
   getpasswd "encryption"
   echo "$PASSWD" > /etc/sysconfig/bfe
   chown ${USER}:root /etc/sysconfig/bfe
   chmod 600 /etc/sysconfig/bfe
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

# If restore then also pass TCE directory for quick look of mydata.tgz backupfile
if [ -n "$MYDATA" ]; then
   echo "$MYDATA" > /etc/sysconfig/mydata
else
   echo "mydata" > /etc/sysconfig/mydata
fi   
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 "$CRON" ] && /etc/init.d/services/crond start

/opt/bootsync.sh

[ -n "$NOAUTOLOGIN" ] && echo "booting" > /etc/sysconfig/noautologin

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