#!/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)
txtblink=$(tput blink)

echo -e "${txtbld}${txtblue}Determining what board we actually working with here...${txtreset}"
boardId=`gnxid`

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

GNX_PATH=/

# 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 ""
echo "${txtblink}BFG Comms unit!${txtreset}"
echo "" ;
echo "" ;
echo "${txtbld}${txtblue}=====[ BFG Setup ]=====${txtreset}"
mkdir -p $GNX_PATH/etc/modprobe.d
echo "options gnxio gpiomap=gnxio" > $GNX_PATH/etc/modprobe.d/gnxio.conf

cp /etc/opkg/opkg.conf /etc/opkg/opkg.conf.backup
echo "
# Package sources 
src v4      http://127.0.0.1:8080/v4/arm
src noarch  http://127.0.0.1:8080/v4/noarch
src rsm     http://127.0.0.1:8080/rsm/v4.2
src tvs     http://127.0.0.1:8080/bfg/v1.1

# Supported architectures
arch    arm  20
arch    noarch   10

# Install directory
dest root /
" > /etc/opkg/opkg.conf


echo " * Updating opkg..."
opkg-cl update

if [ ! -d "$GNX_PATH/var/log/bfg" ] ; then
    echo " * Creating directory $GNX_PATH/var/log/bfg"
    mkdir -p "$GNX_PATH/var/log/bfg"
fi

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

cp /etc/opkg/opkg.conf /etc/opkg/opkg.conf.usb
cp /etc/opkg/opkg.conf.backup /etc/opkg/opkg.conf

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

echo ""
echo "You did good kid, you did real good."
exit 0

