#!/bin/bash

# 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

root=${root:-/dev/mmcblk1p1}
root_type="-t ext4"
root_opts=${root_opts:-"-o data=journal"}

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

echo "Using the following parameters:"
echo " root = '$root'"
echo " root_type = '$root_type'"
echo " root_opts = '$root_opts'"

echo "${txtbld}${txtblue}Figuring out disk geometry based on the kernel cmdline...${txtreset}"

set -- `ls /sys/block`
i=0
for block; do 
CNT=$(echo $root|grep -c $block)
if [ $CNT -gt 0 ]; then
	DISK="/dev/$block"
	PART=$root
fi
 i=$(($i + 1))
done

if [ -z $DISK ]; then
echo "Could not find the disk that goes with partition $root"
echo "Please make sure the device is inserted" 
exit 1
fi

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

echo "Using the following mount options:"
echo " GNX_PATH = '$GNX_PATH'"
echo " DISK = '$DISK'"
echo " PART = '$PART'"


if [ -e $PART ]; then
    echo "The root partition already exists. Will just format the filesystem."
else
	echo "The root partion does not exist. Will have to create a new partition table"
	# 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
	
	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
fi


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

echo ""

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

if [ -z "$DISK" ]; then
        DISK="/dev/mmcblk1"
fi
if [ -z "$PART" ]; then
	PART="/dev/mmcblk1p1"
fi

echo "Using the following mount options:"
echo " GNX_PATH = '$GNX_PATH'"
echo " DISK = '$DISK'"
echo " PART = '$PART'"

#open gnx root up for editing
if [ "$GNX_PATH" == "/" ]; then
	# we are running from the guinnux root so don't do any special mounting/unmounting
	echo ""
else
    #mount $PART on $GNX_PATH and bind device files
    mkdir -p "$GNX_PATH" 1>/dev/null
    mountpoint -q "$GNX_PATH" 1>/dev/null
    if [ "$?" == "0" ]; then
	   echo "Error: $GNX_PATH is already a mountpoint, cannot continue" 1>&2
	   exit 1
    fi
    ls -l $PART
    mount $root_type $root_opts $PART $GNX_PATH 1>/dev/null
    if [ "$?" != "0" ]; then
	   echo "Error: Failed to mount $PART on $GNX_PATH" 1>&2
	 	exit 1	 
    fi
    
    mkdir -p $GNX_PATH/dev
    mkdir -p $GNX_PATH/proc
    mkdir -p $GNX_PATH/sys
    
    mount --bind /dev $GNX_PATH/dev
    mount --bind /proc $GNX_PATH/proc
    mount --bind /sys $GNX_PATH/sys
    if [ "$?" != "0" ]; then
        echo "Error: Failed to bind device files to the Guinnux root" 1>&2
    fi
fi

echo "${txtbld}${txtblue}Updating the Guinnux Installer${txtreset}"
pacman -Sy -dd --force --noconfirm gnx-bbb-installer

export GNX_PATH
exec /usr/bin/gnx-bbb-install

