#!/bin/bash
#
# /etc/rc.d/rc.S:  System initialization script.
#
# Mostly written by:  Patrick J. Volkerding, <volkerdi@slackware.com>
#
# Modified for Porteus by fanthom

PATH=/sbin:/usr/sbin:/bin:/usr/bin

# Mounting proc and sys
mount proc /proc -t proc
mount sysfs /sys -t sysfs

# Remounting the / partition to update mtab
mount -w -o remount /

# Update all the shared library links:
echo "Updating shared library links:  /sbin/ldconfig &"
/sbin/ldconfig &

# T-bit on tmp directories
chmod 1777 /tmp /var/tmp

# Set correct permissions on /root folder
chmod 700 /root

# Only rebuild dependencies if new module(s) are found:
NEWMODS=`find /lib/modules/2.6.* -type f -mindepth 2 -newer /lib/modules/2.6.*/modules.dep 2>/dev/null`
[ "$NEWMODS" = "" ] || { echo "New kernel module(s) found - updating dependencies..."; depmod -a; }

# Initialize udev to manage /dev entries and hotplugging for 2.6.x kernels.
# You may turn off udev by making the /etc/rc.d/rc.udev file non-executable
# or giving the "nohotplug" option at boot, but in the 2.6.x+ kernels udev
# has taken over the job of hotplug (finding hardware and loading the kernel
# modules for it, as well as creating device nodes in /dev).  Realize that
# if you turn off udev that you will have to load all the kernel modules
# that you need yourself (possibly in /etc/rc.d/rc.modules, which does not
# promise to list all of them), and make any additional device nodes that you
# need in the /dev directory.  Even USB and IEEE1394 devices will need to have
# the modules loaded by hand if udev is not used with a 2.6 kernel.  So use it.  :-)
grep -wq nohotplug /proc/cmdline || { [ -x /etc/rc.d/rc.udev ] && sh /etc/rc.d/rc.udev start; }

# Initialize the Logical Volume Manager.
# This won't start unless we find /etc/lvmtab (LVM1) or
# /etc/lvm/backup/ (LVM2).  This is created by /sbin/vgscan, so to
# use LVM you must run /sbin/vgscan yourself the first time (and
# create some VGs and LVs).
if ! grep -q "nohd" /proc/cmdline; then
    if [ -d /etc/lvm/backup ]; then
	echo "Initializing LVM (Logical Volume Manager)"
	# Scan for new volume groups:
	/sbin/vgscan --mknodes --ignorelockingfailure 2> /dev/null
	if [ $? = 0 ]; then
	    # Make volume groups available to the kernel.
	    # This should also make logical volumes available.
	    /sbin/vgchange -ay --ignorelockingfailure >/dev/null 2>&1
	    # LVM automount:
	    blkid | grep /dev/mapper >/tmp/mapper$$
	    if grep -q /dev /tmp/mapper$$; then
		echo -e "\n# LVM partitions" >>/etc/fstab
		LVM=`wc -l /tmp/mapper$$ | cut -d " " -f1`
		grep -wq "noauto" /proc/cmdline && AUTO=noauto || AUTO=auto; x=1
		while [ $x -le $LVM ]; do
		    NAME=`awk NR==$x /tmp/mapper$$ | awk '{print$1}' | cut -d ':' -f1 | sed "s@/dev/mapper/@@"`
		    FS=`awk NR==$x /tmp/mapper$$ | awk '{print$3}' | cut -d '=' -f2 | sed s/'"'//g`
		    mkdir /mnt/$NAME
		    echo "/dev/mapper/$NAME /mnt/$NAME $FS $AUTO,noatime,users,suid,dev,exec 0 0 # AutoUpdate" >>/etc/fstab
		    let x=x+1
		done
	    fi
	    rm /tmp/mapper$$
	fi
    fi
fi

# Open any volumes created by cryptsetup:
if [ -f /etc/crypttab -a -x /sbin/cryptsetup.static ]; then
    # NOTE: we only support LUKS formatted volumes (except for swap)!
    cat /etc/crypttab | grep -v "^#" | grep -v "^$" | while read line; do
    eval LUKSARRAY=( $line )
    LUKS="${LUKSARRAY[0]}"
    DEV="${LUKSARRAY[1]}"
    PASS="${LUKSARRAY[2]}"
    OPTS="${LUKSARRAY[3]}"
    LUKSOPTS=""
    if echo $OPTS | grep -wq ro; then LUKSOPTS="${LUKSOPTS} --readonly" ; fi

    # Skip LUKS volumes that were already unlocked (in the initrd):
    /sbin/cryptsetup.static status $LUKS 1>/dev/null 2>/dev/null && continue
    if /sbin/cryptsetup.static isLuks $DEV 2>/dev/null ; then
	echo "Unlocking LUKS crypt volume '${LUKS}' on device '$DEV':"
	if [ -n "${PASS}" ]; then
	    if [ -f ${PASS} ]; then
		/sbin/cryptsetup.static ${LUKSOPTS} --key-file=${PASS} luksOpen $DEV $LUKS
	    elif [ "${PASS}" != "none" ]; then
		# A password field of 'none' indicates a line for swap:
		echo "${PASS}" | /sbin/cryptsetup.static ${LUKSOPTS} luksOpen $DEV $LUKS
	    fi
	else
	    for i in seq 1 3 ; do
		/sbin/cryptsetup.static ${LUKSOPTS} luksOpen $DEV $LUKS </dev/tty0 >/dev/tty0 2>&1
		[ $? -eq 0 ] && break
	    done
	fi
    elif echo $OPTS | grep -wq swap; then
	# If any of the volumes is to be used as encrypted swap,
	# then encrypt it using a random key and run mkswap:
	echo "Creating encrypted swap on device '$DEV' mapped to '${LUKS}':"
	/sbin/cryptsetup.static --cipher=aes --key-file=/dev/urandom --key-size=256 create $LUKS $DEV
	mkswap /dev/mapper/$LUKS
    fi
    done
fi

# Set the system time from the hardware clock using hwclock --hctosys.
# Check for a broken motherboard RTC clock (where ioports for rtc are
# unknown) to prevent hwclock causing a hang:
grep -q -w rtc /proc/ioports || CLOCK_OPT="--directisa"

if grep -wq "^UTC" /etc/hardwareclock; then
    echo "Setting system time from the hardware clock (UTC)."
    /sbin/hwclock $CLOCK_OPT --utc --hctosys &
else
    echo "Setting system time from the hardware clock (localtime)."
    /sbin/hwclock $CLOCK_OPT --localtime --hctosys &
fi

# Configure ISA Plug-and-Play devices:
[ -r /etc/isapnp.conf ] && /sbin/isapnp /etc/isapnp.conf &

# This loads any kernel modules that are needed.  These might be required to
# use your ethernet card, sound card, or other optional hardware.
# Priority is given first to a script named "rc.modules.local", then
# to "rc.modules-$FULL_KERNEL_VERSION", and finally to the plain "rc.modules".
# Note that if /etc/rc.d/rc.modules.local is found, then that will be the ONLY
# rc.modules script the machine will run, so make sure it has everything in
# it that you need.
if [ -x /etc/rc.d/rc.modules.local -a -r /proc/modules ]; then
    echo "Running /etc/rc.d/rc.modules.local:"
    . /etc/rc.d/rc.modules.local
elif [ -x /etc/rc.d/rc.modules-$(uname -r) -a -r /proc/modules ]; then
    echo "Running /etc/rc.d/rc.modules-$(uname -r):"
    . /etc/rc.d/rc.modules-$(uname -r)
elif [ -x /etc/rc.d/rc.modules -a -r /proc/modules -a -L /etc/rc.d/rc.modules ]; then
    echo "Running /etc/rc.d/rc.modules -> $(readlink /etc/rc.d/rc.modules):"
    . /etc/rc.d/rc.modules
elif [ -x /etc/rc.d/rc.modules -a -r /proc/modules ]; then
    echo "Running /etc/rc.d/rc.modules:"
    . /etc/rc.d/rc.modules
fi

# Configure runtime kernel parameters:
[ -r /etc/sysctl.conf ] && /sbin/sysctl -e -p /etc/sysctl.conf &

# Mount non-root file systems in fstab, but not NFS or SMB
# because TCP/IP is not yet configured, and not proc or sysfs
# because those have already been mounted.
echo "Mounting non-root local filesystems:"
mount -a -v -t nonfs,nosmbfs,nocifs,noproc,nosysfs,nodevpts

# Enable swapping.
swapon -a 2>/dev/null &

# Bind magic_folders
if [ -e /etc/magic_folders/folders.cfg ]; then
    if ! grep -qw "nomagic" /proc/cmdline; then
	echo "Binding magic_folders..."
	num=`wc -l /etc/magic_folders/folders.cfg | cut -d " " -f1`; x=1
	while [ $x -le $num ]; do
	    fst=`awk NR==$x /etc/magic_folders/folders.cfg | cut -d " " -f1`
	    sec=`awk NR==$x /etc/magic_folders/folders.cfg | cut -d " " -f2`
	    if [ ! -d $fst ]; then
		# Add free loop device for .dat file
		x=`grep /dev/loop /proc/mounts | tail -n1 | cut -d " " -f1 | sed 's@/dev/loop@@'`; let y=x+1
		[ -e /dev/loop$y ] || mknod /dev/loop$y b 7 $y
		echo "mount -o loop $fst $sec"
		mount -o loop $fst $sec
	    else
		echo "mount -o bind $fst $sec"
		mount -o bind $fst $sec
	    fi
	    let x=x+1
	done
    fi
fi

# Run serial port setup script:
# CAREFUL!  This can make some systems hang if the rc.serial script isn't
# set up correctly.  If this happens, you may have to edit the file from a
# boot disk, and/or set it as non-executable:
[ -x /etc/rc.d/rc.serial ] && sh /etc/rc.d/rc.serial start

# Carry an entropy pool between reboots to improve randomness.
[ -f /etc/random-seed ] && { echo "Using /etc/random-seed to initialize /dev/urandom."; cat /etc/random-seed > /dev/urandom; }

# Use the pool size from /proc, or 512 bytes:
[ -r /proc/sys/kernel/random/poolsize ] && dd if=/dev/urandom of=/etc/random-seed count=1 bs=`cat /proc/sys/kernel/random/poolsize` 2>/dev/null || dd if=/dev/urandom of=/etc/random-seed count=1 bs=512 2>/dev/null
chmod 600 /etc/random-seed
