#!/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)

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

#establish default for the program
if [ -z "$GNX_PATH" ]; then
	GNX_PATH="/mnt/gnx-root"
fi
if [ -z "$PART" ]; then
	PART="/dev/mmcblk0p1"
fi
if [ -z "$netPkg" ]; then
	# don't do anything, a net-pkg has not been specified to be installed
	echo -e "${txtbld}${txtblue}Skipping networking...${txtreset}"
	exit 0
fi

echo -n -e "${txtund}${txtblue}Installing the net-scripts configuration package to $PART...${txtreset}"
opkg-cl -o "$GNX_PATH" -f /etc/opkg/opkg.conf --cache /var/gnx-installer/packageCache install $netPkg
if [ "$?" != "0" ]; then
	echo -e "${txtbld}${txtred}[ERROR]${txtreset}"
	echo -n "opkg output reads:"
	cat /var/gnx-installer/tmpLog
	exit 1
else
	echo -e "${txtbld}${txtblue}[OK]${txtreset}"
fi

echo -n -e "${txtund}${txtblue}Overwriting interfaces on $PART...${txtreset}"
cp -dvR /etc/network "$GNX_PATH/etc/"
cp -v /etc/network.conf "$GNX_PATH/etc/"
cp -v /etc/resolv.conf "$GNX_PATH/etc/"

if [ "$?" == "0" ]; then
	echo -e "${txtbld}${txtblue}[OK]${txtreset}"
else
	echo -e "${txtbld}${txtred}[ERROR]${txtreset}"
	exit 1
fi

echo -n -e "${txtund}${txtblue}Syncing network settings on $PART and rescue file system...${txtreset}"
mount -o remount,rw /mnt/rescRO
if [ "$?" != "0" ]; then
	echo -e "${txtbld}${txtred}[ERROR]${txtreset}"
	exit 1
fi
cp -dvR "$GNX_PATH/etc/network" /mnt/rescRO/etc
cp -v "$GNX_PATH/etc/network.conf" /mnt/rescRO/etc
cp -v "$GNX_PATH/etc/resolv.conf" /mnt/rescRO/etc

if [ "$?" != "0" ]; then
        echo -e "${txtbld}${txtred}[ERROR]${txtreset}"
	mount -o remount,ro /mnt/rescRO
        exit 1
fi
mount -o remount,ro /mnt/rescRO
if [ "$?" != "0" ]; then
        echo -e "${txtbld}${txtred}[ERROR]${txtreset}"
        exit 1
else
	echo -e "${txtbld}${txtblue}[OK]${txtreset}"
fi

exit 0
