#!/bin/ash 
export PATH=/sbin:/bin:/usr/bin:/usr/sbin
export HOME=/root/compaq

#Mount Proc system
mount -t proc proc /proc >/dev/null 2>&1

#Load external files
. /etc/initrd.default
. /etc/initrd.functions

#Remount in rw just in case
cat  /proc/mounts > /etc/mtab 
mount -o remount,rw / >/dev/null 2>&1

# Set up symlinks
/bin/busybox --install -s


#############################################################
# by Patrick Masotta Serva 3.0.0 (c) 2010-2016
# http://www.vercot.com/~serva/default.html


echo "┌────────────────────────────────────────────────┐"
echo "│        Serva 3.0.0 Automated PXE Server        │"
echo "│   Copyright (c) 2010-2016 by Patrick Masotta   │"
echo "│             www.vercot.com/~serva/             │"
echo "└────────────────────────────────────────────────┘"
sleep 2

initrd="INITRD_N20.GZ"
karch=$(uname -m)
kver=$(uname -r)


    case "$kver" in

        3.12.28-4-default )

            ;;

        3.12.38-44-default )

            ;;

        *)
            sleep 5
            echo "ERROR: Kernel version=$kver is not supported by $initrd."
	    run_shell
    esac


    #SPP2016100.2016_1015.191 patch
    if [ -s /sbin/mount.cifs ] && ! [ -s /usr/lib64/libcap-ng.so.0 ] ; then
	cp ./libcap-ng.so.0.0.0 /usr/lib64/libcap-ng.so.0.0.0
	cp ./libcap-ng.so.0 /usr/lib64/libcap-ng.so.0
    fi
    rm ./*.so.*



    mkdir -p "/lib/modules/$kver/kernel/net/dns_resolver"
    cp "./dns_resolver.ko.$kver"     "/lib/modules/$kver/kernel/net/dns_resolver/dns_resolver.ko"


#early insertions required by cifs.ko
insmod "/lib/modules/$kver/kernel/net/dns_resolver/dns_resolver.ko"

rm ./*.ko.*

#read -n1 -r -p "Press any key to continue..." key
#############################################################



#Enable debug mode
if [ -n "$(cat /proc/cmdline | grep 'd3bug')" ] ; then
    set -xv
fi
# if fusion has triggered debug - output everything
if [ -f /sysroot/bin/hp-ev ] ; then
    if /sysroot/bin/hp-ev CQHVER --format='%{VALUE}' | grep 01 ; then
        set -xv
    fi
fi

#mounts sysfs
mount_sysfs

#udev can handle the events without any help
echo "" > /proc/sys/kernel/hotplug

#Start device manager
start_dev_mgr

# Look for the manifest argument
if [ -n "$(grep 'hp_manifest' /proc/cmdline)" ] ; then
    for token in $(cat /proc/cmdline)
    do
        case $token in
            hp_manifest=*)
                export HP_MANIFEST="${token:12}"
                export HP_FLASH=1
                ;;
        esac
    done
elif [ -n "$(grep 'hp_erase' /proc/cmdline)" ] ; then
    for token in $(cat /proc/cmdline)
    do
        case $token in
            hp_erase)
                export HP_ERASE=1
                ;;
            hp_erase=*)
                export HP_ERASE="${token:9}"
                ;;
        esac
    done
elif [ -n "$(grep 'hp_recovery' /proc/cmdline)" ] ; then
    export HP_FLASH=1
    for token in $(cat /proc/cmdline)
    do
        case $token in
            hp_recovery=*)
                export HP_FLASH_DOWNLOAD="${token:12}"
                ;;
        esac
    done
fi

if [ -n "${HP_FLASH}" ] || [ -n "${HP_ERASE}" ] ; then

    mv /usr/share/plymouth/themes/hp /usr/share/plymouth/themes/hp-bak
    mv /usr/share/plymouth/themes/hp-flash /usr/share/plymouth/themes/hp

    #Start Plymouth
    plymouthd --mode=updates
    #Update model with the newone
    file=/usr/share/plymouth/themes/hp/hp.script
    model=$(cat /sys/class/dmi/id/product_name)
    sed -i "s/_model_/$model/g" $file
    plymouth --show-splash

    #Add ilo module
    HW_MODULES="$HW_MODULES hpilo"

else
    #Start Plymouth
   start_plymouth    
fi

#Load modules
load_modules

# not in update mode so mount the media
if [ -z "${HP_MANFIEST}" ] && [ -z "${HP_FLASH_DOWNLOAD}" ] ; then
    #mount Media cdrom or usb or ntfs
    mount_media
fi


#If manifest was passed then we're in update mode
if [ -n "$HP_MANIFEST" ] || [ -n "$HP_FLASH_DOWNLOAD" ] ; then
    load_network_modules
    /usr/bin/hpnetworkconfig

    mkdir -p /mnt/boot
    mount -t ramfs none /mnt/boot
    mkdir -p /mnt/boot/ip

    plymouth display-message --text='key1:Downloading update image'
    if [ -n "$HP_MANIFEST" ] ; then
        plymouth display-message --text='key2:This may take up to serveral minutes'
    elif [ -n "$HP_FLASH_DOWNLOAD" ] ; then
        plymouth display-message --text='key2:This may take up to serveral minutes (no progress will be displayed)'
    fi
 
    sleep 30 # need to wait for NICs to get configured

    if [ -n "$HP_MANIFEST" ] ; then
        /bin/gaius -c $HP_MANIFEST /mnt/boot/ip
    fi
    if [ -n "$HP_FLASH_DOWNLOAD" ] ; then
        /bin/gaius -i $HP_FLASH_DOWNLOAD /mnt/boot/ip
    fi
    if [ "$?" -ne "0" ]; then
        plymouth display-message --text='key2:Download failed! - unable to continue'
        sleep 30
        plymouth quit
        run_shell
        # /sbin/reboot -f
    fi
fi

if [ -n "$HP_FLASH" ] ; then
    /bin/xmlsmif < /etc/gaiusmount.xml > /dev/null
    if [ "$?" -ne "0" ]; then
        plymouth display-message --text='key2:iLO unresponsive - unable to continue'
        sleep 15
        plymouth quit
        /sbin/reboot -f
    fi
    plymouth display-message --text='key1:Verifying system settings'
    plymouth display-message --text='key2:This may take up to 30 seconds'

    #do the HPBlobl stuff in bg
    write_hpblob_info &

    #Run Gais
    if [ -f /mnt/boot/ip/gaius-debug.img.gz ] ; then
        /bin/gaius /mnt/boot/ip/gaius-debug.img.gz /mnt/boot/ip/vid.img.gz
        retcode=$?
    else
        /bin/gaius /mnt/boot/ip/gaius.img.gz /mnt/boot/ip/vid.img.gz
        retcode=$?
    fi
    sync
    if [ "$retcode" -ne "0" ]; then
        plymouth display-message --text='key1:Error Flashing the NVRam'
        plymouth display-message --text='key2:Please try again.'
        sleep 15
        plymouth quit
        /sbin/reboot -f
    fi
    plymouth --update=100
    sleep 10
    clear
    plymouth quit
    if [ -n "$(cat /proc/cmdline | grep 'cdrom')" ]; then
        for f in /dev/sr*;do
            eject $f >/dev/null 2>&1
        done
        clear
        echo
        read -t 5 -p "Please remove the CDROM and press ENTER or wait five seconds"
    fi
    /sbin/reboot -f
fi

if [ -n "$HP_ERASE" ] ; then
    modprobe hpilo
    sleep 2
    /bin/xmlsmif < /etc/gaiusmount.xml > /dev/null
    hpblob -r -x -k birthcert -f /tmp/birthcert.xml >/dev/null 2>&1
    nanddev=`sh /bin/nand_block.sh 2>/dev/null | grep '^/'`
    nandsize=`blockdev --getsize64 $nanddev`

    plymouth display-message --text='key1:Performing erase operation'
    plymouth display-message --text='key2:This can take a significant amount of time.  Please be patient.'

    sh /bin/nand_dod_erase.sh $nanddev >/dev/null 2>&1 &

    # show progress with plymouth
    continue=1
    totalprogress=0
    while [ -n "$continue" ] ; do
        if [ -f /tmp/securenand.prog ] ; then
            progress=`head -1 /tmp/securenand.prog 2>/dev/null`
            progressdone=`grep done /tmp/securenand.prog 2>/dev/null`
            pass=`head -1 /tmp/securenandpass.prog 2>/dev/null`
            if [ -n "$progressdone" ] ; then
                # we're completely erased
                continue=""
                hpblob -w -x -k birthcert -f /tmp/birthcert.xml >/dev/null 2>&1

                cat<<END>/tmp/lo_reboot.xml
<RIBCL VERSION="2.1"><LOGIN USER_LOGIN="any" PASSWORD="empty">
<RIB_INFO MODE="write"><RESET_RIB /></RIB_INFO>
</LOGIN></RIBCL>
END
                /bin/xmlsmif < /tmp/lo_reboot.xml

            else
                percentfmt=$(( ( progress * 100 / ( nandsize / 1024 / 1024 ) ) / 7 ))
                totalprogress=$(( totalprogress + percentfmt ))
                plymouth --update=$totalprogress
            fi
        fi
        sleep 1
    done

    sync
    plymouth --update=100
    sleep 10
    clear
    plymouth quit
    if [ -n "$(cat /proc/cmdline | grep 'cdrom')" ]; then
        for f in /dev/sr*;do
            eject $f >/dev/null 2>&1
        done
        clear
        echo
        read -t 5 -p "Please remove the CDROM and press ENTER or wait five seconds"
    fi
    /sbin/reboot -f
fi

#Mount the squash filesystem
mount_fs

#Exit a shell if is necesary
if [ -n "$(cat /proc/cmdline | grep 'initrd-shell')" ] ; then
    run_shell
fi

cd "${CHROOT_DIR}"
mkdir -p "${CHROOT_DIR}/proc" "${CHROOT_DIR}/sys" "${CHROOT_DIR}/selinux" 2>/dev/null

mount --move /dev  "${CHROOT_DIR}"/dev || echo '*: Failed to move the ramdisk /dev!'
mount --move /sys  "${CHROOT_DIR}"/sys || echo '*: Failed to move the ramdisk /sys!'
mount -t proc none "${CHROOT_DIR}"/proc || echo '*: Failed to mount the ramdisk /proc!'
mkdir -p "${CHROOT_DIR}"/dev/shm
chmod 1777 "${CHROOT_DIR}"/dev/shm
mount -t tmpfs -o size=2G none "${CHROOT_DIR}"/dev/shm

if [ -n "$(cat /proc/cmdline | grep -i 'cdcache')" ] ; then
    # unmount ${BOOTDEVICEMP} so the new root can mount/unmount
    umount "${BOOTDEVICEMP}" 2>/dev/null
    umount "${CHROOT_DIR}/${BOOTDEVICEMP}" 2>/dev/null
    
    # create new boot.media script to mount the boot media in the chroot
    echo '#!/bin/bash'         > "${CHROOT_DIR}/etc/init.d/boot.d/S05boot.media"
    cat /etc/initrd.default   >> "${CHROOT_DIR}/etc/init.d/boot.d/S05boot.media"
    cat /etc/initrd.functions >> "${CHROOT_DIR}/etc/init.d/boot.d/S05boot.media"
    cat<<END>>"${CHROOT_DIR}/etc/init.d/boot.d/S05boot.media"

    PATH=\$PATH:/root/compaq
    
    mount_media
    
END
    chmod +x "${CHROOT_DIR}/etc/init.d/boot.d/S05boot.media"
fi

#Copy the mount information 
cat /proc/mounts |grep -v "${CHROOT_DIR}" > "${CHROOT_DIR}"/etc/mtab

#Plymouth
#/bin/plymouth update-root-fs --newroot=$CHROOT_DIR

#Move the root to chroot
exec /sbin/switch_root -c "/dev/console" "${CHROOT_DIR}" "/sbin/init" 3 

# If we get here, something bad has happened
echo "---------------------------------------------------------"
echo "ERROR: chroot failed!."
echo "---------------------------------------------------------"
echo
echo "Unable to locate the complete application on the provided media - the boot has failed."
echo "Validate that there are no warnings flagged under the iLO Diagnostics tab and any media used is valid."
echo
run_shell
