#!/bin/sh

# colour for output
txtbld=$(tput bold)
txtund=${txtbld}$(tput sgr 0 1)
txtred=$(tput setaf 1)
txtyellow=$(tput setaf 3)
txtblue=$(tput setaf 4)
txtreset=$(tput sgr0)

# record the exit code if we need to clean up
EXIT_CODE="0"

# check if root is running this
if [ "`id -u`" != "0" ]; then
        echo "${txtbld}${txtred}Permission denied, must be root!${txtreset}" 1>&2
        exit 1
fi

# establish default package list exists
PKG_LIST=""
if [ -e "/var/gnx-installer/gnx-pkglist" ]; then
	PKG_LIST="/var/gnx-installer/gnx-pkglist"
else
        echo -e "${txtbld}${txtred}The package list(/var/installer/gnx-pkglist) could not be found, please reinstall gnx-installer.${txtreset}\n" 1>&2
        echo -e "Aborting...\n" 
        exit 1
fi

if [ -z "$FS_TYPE" ]; then
	FS_TYPE="ext4"
fi

# make necessary directories in case they have been tampered with and clean up
mkdir /mnt/gnx-root -p
mkdir /var/gnx-installer/packageCache -p
rm -f /var/gnx-installer/packageCache/*

echo "Starting Guinnux installer..."
echo    "${txtbld}${txtblue}######################   Guinnux Installer  ########################${txtreset}"
echo    ""
echo    "Welcome to the Guinnux installer. The installer will install\
 the base Guinnux operating system on the SD card.\
 NOTE: This will erase all content on the SD card!" | fold -s

echo    "The installer will now proceed. Before the main setup begins,\
 please confirm the following installation specifications." | fold -s
echo ""

# incase the SD card is /dev/mmcblk"." where "." is not 0, we allow the disk to be specified
if [ -n "$DISK" ]; then
        echo -e -n  "${txtund}${txtblue}Target disk:${txtreset} $DISK\t"
        echo -e -n "\n${txtbld}${txtyellow} WARN: This is not the standard disk device. Installing to\
 this disk should work provided that it is /dev/mmcblk0 during startup.${txtreset}" | fold -s
else
        DISK=/dev/mmcblk0
        echo -e -n  "${txtund}${txtblue}Target disk:${txtreset} $DISK\t"
fi
# check if $DISK is a block device
if [ -b $DISK ]; then
        echo -e "${txtbld}${txtblue}[ OK ]${txtreset}"
else
        echo -e "\n${txtbld}${txtred}$DISK is not a block device, have you inserted the SD card${txtreset}"
	echo "NOTE: you can specify another block device file by setting DISK to its full path"
        echo -e "Aborting...\n"
        exit 1
fi
# determine the partition
NON_STANDARD_BUILD=false
if [ -n "$PART" ]; then
	echo -e "${txtund}${txtblue}Target partition:${txtreset} $PART"
        echo -e "${txtbld}${txtyellow} WARN: This is not the standard partition device. Installing to\
 this partition should work provided that root is set to $PART in the kernel cmdline and that Guinnux root's\
 fstab is edited appropriately so as to remount with the correct fs type and options (do this after the install).${txtreset}" | fold -s
	NON_STANDARD_BUILD=true
else
	PART="${DISK}p1"
	echo -e "${txtund}${txtblue}Target partition:${txtreset} $PART\t"	
fi
echo -e "${txtund}${txtblue}Partition format:${txtreset} $FS_TYPE"
if [ "$FS_TYPE" != "ext4" ]; then
	echo -e -n "${txtbld}${txtyellow} WARN: This is not the standard format for the root partition. Using this\
 formatting should work provided that root_type is set to the name of the file system type in the kernel cmdline and that Guinnux root's\
 fstab is edited appropriately so as to remount with the correct fs type and options (do this after the install).${txtreset}" | fold -s
	NON_STANDARD_BUILD=true
fi
echo ""

# state some more details about the partition setup
echo -e "${txtund}${txtblue}Current partition table (will be lost on install!):${txtreset}"
/sbin/fdisk -l $DISK | grep -v '^$' | fold -s

echo ""


# prompt for if we must continue
while true; do
        read -p "Do you want to overwrite the partition table? (${txtbld}Y${txtreset}es / ${txtbld}N${txtreset}o / ${txtbld}A${txtreset}bort) : " choice
        case $choice in
                [y]* )
                        echo -e "Partition table will be ${txtbld}overwritten${txtreset} when setup begins.\n" ;
                        SAVE=0;
                        break;;
                [n]* )
                        echo -e "Partition table will be ${txtbld}preserved${txtreset} when setup begins...\n" ;
                        SAVE=1;
                        break;;
                [a]* )
                        echo -e "Aborting...\n" ;
                        exit 0;;
        esac
done

# show network installation details
echo "${txtund}${txtblue}Networking:${txtreset}"
netPkg=""
if [ -e /var/network-setup/default/opk_pkg ]; then
        netPkg="$(cat "/var/network-setup/default/opk_pkg")"
        echo "${txtbld}${txtblue}Network scripts package:${txtreset} $netPkg"
else
        echo "${txtbld}${txtyellow}WARNING: The rootfs has no networking enabled. Please name the package required for network configuration."
        echo "Example: echo \"net-scripts-ip175d\" > /var/network-setup/default/opk_pkg${txtreset}"
fi
if [ -e /etc/network/interfaces ]; then
	echo -e "${txtbld}${txtblue}The following interfaces file will overwrite the default:${txtreset}"
	cat /etc/network/interfaces | sed -e 's|\(.*\)|\t\1|g'
fi

echo    ""
echo    "${txtbld}${txtblue}#######################################################################${txtreset}"

# prompt for if we must continue
while true; do
        read -p "Please read the specifications above and choose to proceed or not (y/n)?" choice
        case $choice in
                [y]* )
                        echo -e "Beginning setup...\n" ;
                        break;;
                [n]* )
                        echo -e "Aborting...\n" ;
                        exit 0;;
        esac
done

if [ "$SAVE" == 0 ]; then
    echo "${txtbld}${txtblue}Creating new empty DOS partition table on $DISK...${txtreset}"
    fdisk $DISK > /dev/null 2>&1 << EOF
o
v
w
EOF

    echo "${txtbld}${txtblue}Creating new partition on $DISK...${txtreset}"
    fdisk -u $DISK > /dev/null 2>&1 << EOF
n
p
1
2048

v
w
EOF

else
    echo "${txtbld}${txtblue}Partition table on $DISK will not be changed${txtreset}..."
fi

echo "${txtbld}${txtblue}Creating $FS_TYPE filesystem on $PART...${txtreset}"
mkfs.$FS_TYPE $PART
if [ "$?" != "0" ]; then
        echo "Error: Failed to format the Guinnux root with \"$FS_TYPE\"" 1>&2
        exit "$?"
fi

echo ""

# establish GNX_PATH
if [ -z "$GNX_PATH" ]; then
	GNX_PATH="/mnt/gnx-root"
fi

# open the Guinnux root for editing
GNX_PATH="$GNX_PATH" PART="$PART" openGnx
if [ "$?" != "0" ]; then
	echo "Error: Failed to open the Guinnux file system for installation" 1>&2 
	exit "$?"
fi
echo ""

# install all packages in order given in gnx-pkglist
GNX_PATH="$GNX_PATH" PKG_LIST="$PKG_LIST" installToGnx
if [ "$?" != "0" ]; then
        echo "Error: Failed to install all packages to the Guinnux file system" 1>&2
	EXIT_CODE="$?"
fi
echo ""

# finalize networking
echo "${txtbld}${txtblue}Finalizing networking...${txtreset}"
GNX_PATH="$GNX_PATH" PART="$PART" netPkg="$netPkg" networkGnx
if [ "$?" != "0" ]; then
        echo "Error: Failed to finalize networking" 1>&2
        EXIT_CODE="$?"
fi
echo ""

# sync openssh settings for the Guinnux root and dropbear on rescue
GNX_PATH="$GNX_PATH" sshGnxSetup
if [ "$?" != "0" ]; then
        echo "Error: Failed to sync secure shell settings" 1>&2
        EXIT_CODE="$?"
fi
echo ""

# close Guinnux
GNX_PATH="$GNX_PATH" PART="$PART" DISK="$DISK" closeGnx
if [ "$?" != "0" ]; then
	echo "Error: Failed to close the Guinnux file system, undefined behaviour may follow" 1>&2
	exit "$?"
fi
echo ""

# exit with success if we reach here
echo "Ending installation..."
echo "Removing logs and package cache..."
/bin/rm -f /var/gnx-installer/tmpLog
/bin/rm -f /var/gnx-installer/packageCache/*

# notify user of changes should be made if they used expert options
if [ ${NON_STANDARD_BUILD} == true ]; then
	echo -e -n "${txtbld}${txtyellow} PLEASE NOTE: You have provided expert options for this installation by altering\
 the default partition and/or default formatting options. For the partition to boot you will have to edit $PART -> /etc/fstab\
 appropriately and you must provide the following to exec in the RedBoot boot script: \'exec -c \"root=$PART root_type=<name of file system type> root_opts=<any options you want to 
include>\
 \"\'${txtreset}" | fold -s
fi

echo ""
exit "$EXIT_CODE"

