#!/bin/bash

# Written by Patrick Verner and Jason Vasquez.
# Code clean-ups by Gert Hulselmans.
# Amended by Dick Burggraaff (burdi01).

export PATH="/bin:/sbin:/usr/bin:/usr/sbin"

VERSION="2012_10_10"
ISO_VERSION="pmagic_$VERSION.iso"
MEM="$((298*1024))"

NORMAL="$(echo -e '\033[0;39m')"
BLUE="$(echo -e '\033[1;34m')"
CYAN="$(echo -e '\033[1;36m')"
GREEN="$(echo -e '\033[1;32m')"
MAGENTA="$(echo -e '\033[1;35m')"
RED="$(echo -e '\033[1;31m')"
YELLOW="$(echo -e '\033[1;33m')"

CURSOFF="$(echo -e '\033[?25l')"
CURSON="$(echo -e '\033[?25h')"

DONE () { echo -e "${GREEN}DONE${NORMAL}\n" ;}

FAILED () {
   echo ${NORMAL}
   echo "You are now on the command line."
   echo "Commands like \"ls\", \"cat\", and \"more\" are at your disposal."
   echo "Use <Shift+PageUp/Down> to scroll up and down."
   echo "When done type \"exit\" to reboot the system."
   echo ${CURSON} ; setsid cttyhack bash ; reboot -f
}

do_sqfs () {
   echo -n "${BLUE}Mounting PMAGIC_$VERSION.SQFS... "

   if ! mount -r -t squashfs /$1/PMAGIC_$VERSION.SQFS /br_sqfs ; then
      echo -e "\n${RED}Mounting /$1/PMAGIC_$VERSION.SQFS failed." ; FAILED
   fi

   mount -t tmpfs tmpfs /br_ram

   # aufs2 (http://aufs.sourceforge.net)
   if ! mount -t aufs -o br:/br_ram=rw:/br_fmu=ro:/br_sqfs=ro aufs /union ; then
      echo -e "\n${RED}Mounting the aufs union failed." ; FAILED
   fi

   mount -t tmpfs tmpfs /union/tmp         # for chromium
   chmod 1777 /union/tmp/                  # for syslinux
   mkdir -p /union/tmp/scripts             # for scripts from pmodules

   DONE
}

# ==============================================================================

# Show progress
dots () {
   set +x

   while [ -d /proc/$1 ]; do
      echo -n '.' ; usleep 100000
   done

   if grep -qe "[Tt]racing" /proc/cmdline ; then
      set -x
   fi
}

# List pmodules and scripts
pmods () {
   ls $1/*.{xz,t?z,deb} $1/scripts/* 2> /dev/null
}

do_default () {
   echo -n "${BLUE}Copying files to RAM ${YELLOW}"
   mount -t tmpfs tmpfs /sqfs_disk
   cp $1/PMAGIC_$VERSION.SQFS /sqfs_disk &
   dots $!
   echo -e "\n"

   do_sqfs /sqfs_disk

   [ ".$(pmods $1) .$(pmods /dev_mnt/$directory/pmagic/pmodules)" != ". ." ] \
      && touch /union/tmp/mount_media
}

do_live () {
   do_sqfs $1
   touch /union/tmp/livemedia
}

do_switch () {
   echo $1 > /union/tmp/pmagic_device
   echo $ISO_PATH > /union/tmp/pmagic_iso_path

   killall -q klogd syslogd systemd-udevd

   rm -Rf /union/etc/modprobe.d ; mv /etc/modprobe.d /union/etc
   mv /var/log/messages /union/var/log
  
   umount -nfl /dev/loop0 /dev/loop1 /sqfs_disk /br_ram 2> /dev/null
   mount --move /dev /union/dev
   mount --move /sys /union/sys
   mount --move /proc /union/proc
   mount --move /run /union/run

   if echo $- | grep -q x ; then
      echo -n "${MAGENTA}[Tt]racing >>> ${NORMAL}" ; read a
   fi
 
   exec switch_root /union "/sbin/init"

}

# ==============================================================================

_M () { echo "${YELLOW}$(($1/1024))${RED}" ;}

find_pmagic () {
   if [ ! -e $1/pmagic/pmodules/PMAGIC_$VERSION.SQFS ]; then
      umount /test_mnt &> /dev/null
      return
   fi

   DONE

   if ! grep -q livemedia /proc/cmdline ; then

      M=$(awk '/^MemTotal/ {print $2}' /proc/meminfo)
      if [ $M -lt $MEM ]; then
         echo "${RED}To run from RAM Parted Magic must have at least $(_M $MEM) MB available,"
         echo "but only $(_M $M) MB was detected."
         echo "Select a 'Live' option from the menu after rebooting the system."
         FAILED
      fi

      do_default $1/pmagic/pmodules

      umount -d /test_mnt &> /dev/null
      umount -d /dev_mnt &> /dev/null

   else

      do_live $1/pmagic/pmodules

      mkdir /union/media/$dev
      if [ ".$ISO_PATH" = "." ]; then
         mount --move /test_mnt /union/media/$dev
      else
         mount --move /dev_mnt /union/media/$dev
         mkdir /union/media/iso
         mount --move /test_mnt /union/media/iso
      fi

   fi

   do_switch /dev/$dev
}

find_pxe () {
   # Merge all /PMAGIC_$VERSION.SQFS?? parts back together to one PMAGIC_$VERSION.SQFS file.
   # This is only needed when initrd.img consisted of multiple initrd.img files to avoid the
   # problem with some tftp servers which can't transfer files bigger than 32MB.
   if [ -e /PMAGIC_$VERSION.SQFS00 ]; then
      FF=`ls /PMAGIC_$VERSION.SQFS* | grep -v PMAGIC_$VERSION.SQFS00`
      for F in $FF ; do
         cat $F >> /PMAGIC_$VERSION.SQFS00 ; rm $F
      done
      mv /PMAGIC_$VERSION.SQFS00 /PMAGIC_$VERSION.SQFS
   fi

   [ -e /PMAGIC_$VERSION.SQFS ] || return

   # The medium is in memory, copying makes no sense
   do_live ""

   mkdir -p /union/media/pxe/${directory}/pmagic/pmodules/scripts
   mv /pmagic/* /union/media/pxe/${directory}/pmagic &> /dev/null
   mv /modules/* /union/media/pxe/${directory}/pmagic/pmodules &> /dev/null
   mv /scripts/* /union/media/pxe/${directory}/pmagic/pmodules/scripts &> /dev/null

   do_switch pxe
}

find_memdisk () {
   MEMDISK_LOC=$(memdiskfind) ; [ $? = 0 ] || return

   # We found a MEMDISK mapped disk, set up phram
   modprobe phram phram=memdisk,${MEMDISK_LOC}
   # Load mtdblock, the memdisk will be /dev/mtdblock0
   modprobe mtdblock
   sleep 1

   dev=mtdblock0
   if ! mount -r /dev/$dev /test_mnt ; then
      echo "${RED}Booting the memdisk-mapped ISO failed."
      echo "Did you specify the correct vmalloc value -- at least (isosize + 32) MB --"
      echo "in your syslinux.cfg *AND* the isolinux.cfg in the ISO ?"
      FAILED
   fi

   # The iso is in memory, copying makes no sense
   do_live /test_mnt/${directory}/pmagic/pmodules

   mkdir /union/media/$dev
   mount --move /test_mnt /union/media/$dev

   do_switch /dev/$dev
}

# ==============================================================================

# Make some needed directories
mkdir -p /union /br_ram /br_fmu /br_sqfs \
   /sqfs_disk /test_mnt /dev_mnt \
   /dev /mnt /proc /sys /tmp /var/log

# Mount kernel file systems
mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev
mount -t tmpfs tmpfs /run

if grep -qe "[Tt]racing" /proc/cmdline ; then
   set -x
fi

# Start logging
if ! grep -q lowram /proc/cmdline ; then
   syslogd
   klogd -c 1
fi

echo "${CURSOFF}"

# Process command line options
get_opt () { echo "$@" | cut -d "=" -f 2 ;}

for i in $(cat /proc/cmdline); do
   case $i in
      blacklist=*)     blacklist=$(get_opt $i | tr ":" " ")  ;;
      directory=*)     directory=$(get_opt $i) ;;
      iso_location=*)  iso_location=$(get_opt $i)  ;;
      iso_filename=*)  ISO_VERSION=$(get_opt $i) ;;
      root=*)          root=$(get_opt $i)  ;;
      label=*)         label=$(get_opt $i)  ;;
      modprobe=*)      modprobe=$(get_opt $i | tr ":" " ")  ;;
      uuid=*)          uuid=$(get_opt $i) ;;
   esac
done

# Assemble fmu.sqfs if split PXE is used
if [ -e /fmu.sqfs00 ]; then
   FF=`ls /fmu.sqfs* | grep -v fmu.sqfs00`
   for F in $FF ; do
      cat $F >> /fmu.sqfs00 ; rm $F
   done
   mv /fmu.sqfs00 /fmu.sqfs
fi
   
# The PM kernels have squashfs builtin, but if yours does not
# then provide the squashfs module in /lib
insmod /lib/squashfs.ko &> /dev/null
if ! mount -r -t squashfs /fmu.sqfs /br_fmu ; then
   echo "${RED}Mounting the fmu.sqfs failed." ; FAILED
fi

ln -fns /br_fmu/lib/firmware /lib
ln -fns /br_fmu/lib/modules /lib
ln -fns /br_fmu/lib/udev /lib

if [ ! -d /lib/modules/$(uname -r) ]; then
   echo "${RED}The bzImage and initrd.img / pmagic<version>.sqfs files"
   echo "are not from the same release." ; FAILED
fi

mkdir -p /dev/pts
mount -t devpts devpts /dev/pts &> /dev/null

echo -n "${BLUE}Setting up system devices... ${NORMAL}"

# Add black listed modules from /proc/cmdline
rm -f /etc/modprobe.d/cmdline.conf &> /dev/null
for i in ${blacklist}; do
   echo blacklist $i >> /etc/modprobe.d/cmdline.conf
done

# If ahci is not loaded before udev the internal disk may not become /dev/sda
if ! grep -q noahci /proc/cmdline ; then
   modprobe ahci &> /dev/null
fi

# Modprobe modules from /proc/cmdline
for i in $modprobe; do
   modprobe $(echo $i | tr "~" " ")
done

# Start udev
echo > /proc/sys/kernel/hotplug
echo 120 > /sys/class/firmware/timeout
UDEV_LOG=0 /lib/systemd/systemd-udevd -d
udevadm trigger --action=add --type=subsystems
udevadm trigger --action=add --type=devices
udevadm settle --timeout=120

mdadm --examine --scan > /etc/mdadm.conf
mdadm --stop --scan &> /dev/null
mdadm --assemble --scan &> /dev/null

DONE

# Module work around stuff
if [ "`lsmod | grep ehci_hcd`" != "" ]; then
   modprobe -r ehci-hcd
   sleep 1
   modprobe ehci-hcd ignore_oc=1
fi

# Dump to shell
if grep -q initrd.img_shell /proc/cmdline ; then
   echo -n "${GREEN}" ; busybox ; echo -n "${NORMAL}"
   echo -n "${CURSON}" ; setsid cttyhack bash ; echo "${CURSOFF}"
fi

# PXE : everything in initrd.img, no mounts or loops necessary
find_pxe

# MEMDISK mapped disks in memory, no loops necessary
find_memdisk

echo -n "${BLUE}Searching for PMAGIC_$VERSION.SQFS...${YELLOW} "

# Mount an ISO
iso () {
   for D in "" pmagic/ images/ ; do
      if [ -e /test_mnt/${iso_location}/$D$ISO_VERSION ]; then
         mount --move /test_mnt /dev_mnt
         ISO_PATH=${iso_location}/$D$ISO_VERSION
         mount -r /dev_mnt/$ISO_PATH /test_mnt
         find_pmagic /test_mnt
         ISO_PATH=
         mount --move /dev_mnt /test_mnt
      fi
   done
}

_device_list () {
   if grep -q device_list /proc/cmdline ; then
      echo -en "\n$@ "
   fi
}

# Mount via a device
root () {
if [ ".$root" != "." ]; then
   _device_list $root
   [ $PASSES -lt 10 ] && DIRECT=direct
   mount "$root" /test_mnt &> /dev/null
   dev=$(grep test_mnt /proc/mounts | awk '{print $1}' | awk -F /dev/ '{print $2}')
   iso ; find_pmagic /test_mnt/$directory
fi
}

# Mount via a label
label () {
if [ ".$label" != "." ]; then
   _device_list $label
   [ $PASSES -lt 10 ] && DIRECT=direct
   mount LABEL="$label" /test_mnt &> /dev/null
   dev=$(grep test_mnt /proc/mounts | awk '{print $1}' | awk -F /dev/ '{print $2}')
   iso ; find_pmagic /test_mnt/$directory
fi
}

# Mount via a (partial) UUID
uuid () {
if [ ".$uuid" != "." ]; then
   _device_list $uuid
   [ $PASSES -lt 10 ] && DIRECT=direct
   UUID=$(blkid | grep $uuid | awk -F 'UUID="' '{print $2}' | awk -F '"' '{print $1}')
   if [ ".$UUID" != "." ]; then
      mount UUID="$UUID" /test_mnt &> /dev/null
      dev=$(grep test_mnt /proc/mounts | awk '{print $1}' | awk -F /dev/ '{print $2}')
      iso ; find_pmagic /test_mnt/$directory
   fi
fi
}

# List removable devices
removable () {
   ( cd /sys/block
     for DD in "$@" ; do
        for D in $(ls -d $DD* 2> /dev/null) ; do
            if [ ".$(cat $D/removable 2> /dev/null)" = ".1" ]; then
               ( cd /dev ; ls $D* 2> /dev/null )
            fi
        done
     done
   )
}

# List devices to scan
# Booted from: 49 = syslinux = USB ; 51 = isolinux = CD
device_list () {
   if [ $PASSES -lt 10 ] || grep -q removableonly /proc/cmdline ; then
      case $(cat /proc/sys/kernel/bootloader_type) in
         49)  removable sd ;;
         51)  removable sr ;;
         *)   removable sd sr vd ;;
      esac
   else
      ( cd /dev ; ls sd* ; ls sr* ; ls vd* ; ls md* ) 2> /dev/null
   fi
}

# The big loop
PASSES=0 ; while [ $PASSES -lt 30 ]; do
   sleep 1
   DIRECT= ; root ; label ; uuid
   if [ ".$DIRECT" = "." ]; then
      DEVICE_LIST="$( device_list | tr "\n" " ")"
      _device_list $DEVICE_LIST

      for dev in $DEVICE_LIST ; do
         mount /dev/$dev /test_mnt &> /dev/null
         iso ; find_pmagic /test_mnt/$directory
      done
   fi
   let PASSES=PASSES+1
done

# Everything failed
echo -e "\n\n${RED}The PMAGIC_$VERSION.SQFS file could not be found."
echo "Report this incident to the forum and if possible attach"
echo "a directory listing of the media."
echo
echo "Example:"
echo "${YELLOW}mount /dev/sr0 /mnt"
echo "ls -lR /mnt${RED}"
echo
echo "At least report the full path and name (including upper and lower case)"
echo "or the absence of any pmagic sqfs files."
FAILED

