#!/bin/sh
# RC Script for Tiny Core Linux 
# (c) Robert Shingledecker 2004,2005,2006,2007,2008
# Several modifications for speed by Curaga
. /etc/init.d/tc-functions
USER="tc"
TCEAPPS="/tmp/tce/"
TCLOOP="/tmp/tcloop"
MYMENU="/usr/local/tce.menu"
TCEICONS="/usr/local/tce.icons"
TCEINSTALLED="/usr/local/tce.installed"
TCEMENU="/usr/local/tce.menu/menu"
TCEWBAR="/usr/local/tce.wbar"
INSTALLED=""

gettceapps(){
   for FILE in `ls $1/*.tce* 2>/dev/null` 
   do
      EXT=${FILE##*.}
      if stringinstring "tce" "$EXT"; then
         BASE=$(getbasefile "$FILE" 1)
         echo -n " ${YELLOW}$BASE${NORMAL}"
         tar -C / -zxf "$FILE" >/dev/null
         case "$EXT" in *m*) NEW_MODULES=1 ;; esac
         case "$EXT" in *l*) NEW_LIBS=1 ;; esac
         if [ ! -x "$TCEINSTALLED"/"$BASE" ]; then  
            touch "$TCEINSTALLED"/"$BASE"         
         fi                                       
      fi
   done
   
   for FILE in `ls $1/*.tcz* 2>/dev/null` 
   do
      EXT=${FILE##*.}
      if stringinstring "tcz" "$EXT"; then
        BASE=$(getbasefile "$FILE" 1)
        echo -n " ${YELLOW}$BASE${NORMAL}"
	[ -d /tmp/tcloop/"$BASE" ] || mkdir -p /tmp/tcloop/"$BASE"
	mount "$FILE" /tmp/tcloop/"$BASE" -o loop 
 
        APPNAME=$BASE tcz-symlinker --dir > /dev/null 2>&1
        APPNAME=$BASE tcz-symlinker > /dev/null 2>&1
	
	if [ -f /tmp/tcloop/"$BASE"/user.tar.gz ]; then
		tar xzf /tmp/tcloop/"$BASE"/user.tar.gz -C / > /dev/null 2>&1
	fi
         
        case "$EXT" in *m*) NEW_MODULES=1 ;; esac
        case "$EXT" in *l*) NEW_LIBS=1 ;; esac
        if [ -x "$TCEINSTALLED"/"$BASE" ]; then  
           "$TCEINSTALLED"/"$BASE"               
        else                                     
           touch "$TCEINSTALLED"/"$BASE"         
        fi                                       
      fi
   done
}

setupHome(){
   tar -C /etc/skel -cf - . | tar -C /home/"$USER" -xf -
   printf 'wm: %s\nicons: %s\n' "$DESKTOP" "$ICONS" > /home/"$USER"/.desktop
   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
}

tceSetup(){
   [ -d "$TCEINSTALLED" ] || mkdir "$TCEINSTALLED"
   [ -d "$TCEAPPS" ] || mkdir "$TCEAPPS"
   [ -d "$MYMENU" ] || mkdir "$MYMENU"
   [ -d "$TCEICONS" ] || mkdir "$TCEICONS"
   [ -d "$TCLOOP" ] || mkdir "$TCLOOP"
   chgrp staff "$TCEAPPS" "$TCEINSTALLED" "$MYMENU" "$TCEICONS" "$TCLOOP"
   chmod g+w "$TCEAPPS" "$TCEINSTALLED" "$MYMENU" "$TCEICONS" "$TCLOOP"
   sync
}

### 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
# usleep_progress

# 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}"

# 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
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#*=} ;;
    	   opt*) MYOPT=${i#*=} ;;
    	   local*) LOCAL=${i#*=} ;;
    	   dosswapfile*) DOSSWAP=1; SWAPFILE=${i#*=} ;;
    	   tce*) TCE=${i#*=} ;;
    	   resume*) RESUME=${i#*=} ;;
  	   host*) HOST=1 ;;
    	   settime*) SETTIME=${i#*=} ;;
    	  esac
      ;;
      *)
	  case $i in
	   nofstab) NOFSTAB=1 ;;
	   syslog) SYSLOG=1 ;;
	   noutc) NOUTC=1 ;;
	   nodhcp) NODHCP=1 ;;
	   checkfs) CHECKFS=1 ;;
	   noicons) NOICONS=1 ;;
	   nolocal) NOLOCAL=1 ;;
	   noswap) NOSWAP=1 ;;
	   secure) SECURE=1 ;;
	   protect) PROTECT=1 ;;
	   ssh) SSH=1 ;;
	   cron) CRON=1 ;;
	   laptop) LAPTOP=1 ;;
	   base) ONLYBASE=1 ;;
	   pause) PAUSE=1 ;;
	  esac
      ;;
  esac
done
echo "${GREEN}Boot options checked.${NORMAL}"

[ -n "$WAITUSB" ] && sleep "$WAITUSB"
modprobe scsi_wait_scan
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=$!
fi
mv /tmp/98-tc.rules /etc/udev/rules.d/. 2>/dev/null
/sbin/udevcontrol reload_rules &

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

if [ -n "$CHECKFS" ]; then
   touch /etc/sysconfig/checkfs
   wait $fstab_pid
   for FS in `grep ext[2,3] /etc/fstab|cut -f1 -d" "`; do
     if grep -q "$FS" /etc/mtab; then
        echo "${GREEN}Skipping ${YELLOW}$FS ${BLUE}already mounted.${NORMAL}"
     else
         echo -n "${BLUE}Checking filesystem: ${YELLOW}$FS${NORMAL} "
         /sbin/e2fsck -fp "$FS" &
         rotdash $!
     fi
   done
   echo "${RED}Standby System rebooting...${NORMAL}"
   reboot
   exit
fi

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

if [ -n "$NOLOCAL" ]; then
   echo "${BLUE}Ignoring local partition/file seek as requested.${NORMAL}"
else
   wait $fstab_pid
   if [ -n "$LOCAL" ]; then
      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
   else
      LOCAL_DEVICE="$(autoscan 'tclocal' 'd')"
      if [ -n "$LOCAL_DEVICE" ]; then
        mount /mnt/"$LOCAL_DEVICE" -o suid && mount --bind /mnt/"$LOCAL_DEVICE"/tclocal /usr/local
     else LOCAL_DEVICE="$(autoscan 'tclocal' 'f')"
        [ -n "$LOCAL_DEVICE" ] && mount /mnt/"$LOCAL_DEVICE" && mount -o loop,suid /mnt/"$LOCAL_DEVICE"/tclocal /usr/local
     fi 
   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
     /sbin/depmod -ae 2>/dev/null
   fi  	
fi

tceSetup

ICONS="wbar"
[ -n "$NOICONS" ] && ICONS=0

if [ -z "$DESKTOP" ]; then
   DESKTOP="$(egrep . /etc/sysconfig/tcdesktop 2>/dev/null | cut -d\= -f2)
   [ -z "$DESKTOP" ] && DESKTOP="jwm"
fi
echo "DESKTOP=\"$DESKTOP\"" >> /etc/sysconfig/tcdesktop

if [ -n "$USER" ]; then
   if ! grep "$USER" /etc/passwd >/dev/null; then addUser; fi
else
   USER="$(egrep . /etc/sysconfig/tcuser 2>/dev/null | cut -d\= -f2)
   [ -z "$USER" ] && USER="tc"
fi
echo "$USER" > /etc/sysconfig/tcuser
mkdir -p /home/"$USER"

unset CRYPTO_SETUP
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 "/mnt/$CRYPTOHOME/$TCHOME" ]; then
         echo "${GREEN}Mounting encrypted tchome file on /mnt/"$MYHOME" as /home/tc.${NORMAL}"
         modprobe aes
         modprobe cryptoloop
         echo "${GREEN}Please enter your encrypted home password..${NORMAL}"
         mount "/mnt/$CRYPTOHOME/$TCHOME" /home/"$USER" -oencryption=aes 
         CRYPTOHOME_SETUP=1
      fi
   else
      echo "Device not found! Ignoring persistent CRYPTOHOME request!"
   fi  
fi
[ ! "$CRYPTOHOME_SETUP" ] && setupHome

unset HOME_SETUP
if [ -n "$MYHOME" ]; then
   wait $fstab_pid
   PARTITION=${MYHOME##/dev/}
   find_mountpoint "$PARTITION"
   if [ -n "$MOUNTPOINT" ]; then
      [ "$MOUNTED" == "yes" ] || mount "$MOUNTPOINT"
      if [ -d "/mnt/$MYHOME/home/$USER" ]; then
         mount --bind "/mnt/$MYHOME/home" /home
         HOME_SETUP=1
      else
         mkdir -p "/mnt/$MYHOME/home/$USER"
         mount --bind "/mnt/$MYHOME/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"
      if [ -d /mnt/"$MYOPT"/opt ]; then
         mount --bind /mnt/"$MYOPT"/opt/ /opt/
         OPT_SETUP=1
      else
         rsync -az /opt /mnt/"$MYOPT"/
         mount --bind "/mnt/$MYOPT"/opt/ /opt/
      fi
   else
      "Echo invalid device specified. Skipping persistent opt request!"
   fi
fi
if [ ! "$OPT_SETUP" ]; then
   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
fi

[ -n "$SSH" ] && /etc/init.d/dropbear start >/dev/null && echo " ${GREEN}ssh started.${NORMAL}"

if [ -n "$CRON" ]; then
  /usr/sbin/crond
  if [ "$?" == 0 ]; then echo " ${GREEN}cron started.${NORMAL}"; fi
fi
if [ -n "$LAPTOP" ]; then 
{
   modprobe ac && modprobe battery 
   modprobe yenta_socket || modprobe i82365 
   /sbin/udevtrigger &
} >/dev/null 2>&1
   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 "$DOSSWAP" ]; then
   [ -z "$SWAPFILE" ] && SWAPFILE="$(autoscan 'tc.swp' 'f')"
   if [ -n "$SWAPFILE" ]; then
      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
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

if [ -n "$ONLYBASE" ]; then
   echo "${GREEN}Skipping TCE Application Extensions as requested on the command line.${NORMAL}"
   MOUNTPOINT="/tmp"; TCE_DIR="tce"
else
   # First check cdrom for extra apps
   if [ -d /cdrom/tce ]; then 
      MOUNTPOINT="/cdrom"
      gettceapps "$MOUNTPOINT"/tce
   fi
   # Next search for tce and setup tce folder
   [ -z "$TCE" ] && TCE="$(autoscan 'tce' 'd')"/tce
   if [ "$TCE" != "/tce" ]; then
      TCE_DEVICE="${TCE%%/*}"
      TCE_DIR="${TCE#*/}"
      if [ "$TCE_DEVICE" = "$TCE_DIR" ]; then TCE_DIR="tce"; fi
      find_mountpoint "$TCE_DEVICE"
      if [ -n "$MOUNTPOINT" ]; then
         echo "${BLUE}Checking for Tiny Core Applications... ${NORMAL}"
         if [ "$MOUNTED" == "yes" ]; then
            if [ ! -d "$MOUNTPOINT"/"$TCE_DIR" ]; then
               mkdir "$MOUNTPOINT"/"$TCE_DIR"
            else
               [ "$MOUNTPOINT"/"$TCE_DIR" == "/cdrom/tce" ] || gettceapps "$MOUNTPOINT"/"$TCE_DIR"
            fi
         else
            mount "$MOUNTPOINT"
            if [ $? == 0 ]; then
               UMOUNT="yes"
               if [ ! -d "$MOUNTPOINT"/"$TCE_DIR" ]; then
                  mkdir "$MOUNTPOINT"/"$TCE_DIR"
               else
                  gettceapps "$MOUNTPOINT"/"$TCE_DIR"
               fi
            fi
         fi
      fi
   else
      MOUNTPOINT="/tmp"; TCE_DIR="tce"
   fi
   [ -n "$NEW_MODULES" ] && /sbin/depmod -a 2>/dev/null
   [ -n "$NEW_LIBS" ] && /sbin/ldconfig  2>/dev/null
fi

echo "$MOUNTPOINT" > /etc/sysconfig/tce.mount
echo "$MOUNTPOINT"/"$TCE_DIR" > /opt/.tce_dir
chown "$USER".staff "$MOUNTPOINT"/"$TCE_DIR" /opt/.tce_dir
chmod g+w /opt/.tce_dir
chown -R "$USER".staff "$TCEINSTALLED"
sync

[ -z "$ONLYBASE" ] && echo "${GREEN} done. ${NORMAL}"

/etc/init.d/tc-restore.sh

if [ -z "$LANGUAGE" ]; then
   LANGUAGE="$(egrep . /etc/sysconfig/language 2>/dev/null | cut -d\= -f2)"
   [ -n "$LANGUAGE" ] || LANGUAGE="C"
fi
echo -n "${GREEN}Setting Language to ${MAGENTA}$LANGUAGE"
echo "LANG=$LANGUAGE" > /etc/sysconfig/language
echo "${GREEN} Done.${NORMAL}"

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

if [ -z "$TZ" ]; then
   TZ="$(egrep . /etc/sysconfig/timezone 2>/dev/null | cut -d\= -f2)"
   [ -n "$TZ" ] || TZ="UTC"
fi
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 "$NODHCP" ]; then
  echo "${GREEN}Skipping DHCP broadcast/network detection as requested on boot commandline.${NORMAL}"
else
  /etc/init.d/dhcp.sh &
fi

# After restore items 
[ -n "$SETTIME" ] && /usr/bin/getTime.sh
[ -n "$DESKTOP" ] && sed -i "s/^wm:.*$/wm: $DESKTOP/" /home/"$USER"/.desktop 
# /etc/init.d/adduser_final.sh "$USER"

# Setup initial tce menu and wbar
cp /usr/share/jwm/tce/menu_template "$TCEMENU"
cp /usr/share/wbar/dot.wbar "$TCEWBAR"
chown "$USER".staff "$TCEMENU" "$TCEWBAR"
chmod g+w "$TCEMENU" "$TCEWBAR"

# Create the tce menu
for F in `ls -1 "$MYMENU"/* | sort -f 2>/dev/null`; do
  APPNAME=`basename "$F"`
  [ "$APPNAME" == "menu" ] || sudo -u $USER /usr/bin/desktop.sh $APPNAME booting
done

echo "${BLUE}Checking for Startup Scripts... ${NORMAL}"
for F in $(find /usr/local/tce.installed/ -perm -755 -type f); do "$F"; done        
echo "${GREEN}Done.${NORMAL}"

/opt/bootlocal.sh &

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