#!/bin/sh

clear

if [ -f /etc/motd ]; then
    cat /etc/motd
fi

# Note that /dev should be handled by devtmpfs
# Make sure this file will be executable

mount -t proc none /proc
mount -t sysfs sysfs /sys

#################################################################
### There should be at least one network interface to proceed ###
#################################################################

echo "Discovering network interfaces..."
sleep 5

if [ -z "$(ls /sys/class/net/ | grep -v '^lo$')" ]; then
    dialog --msgbox "Butterknife was unable to detect any network interfaces,\
        are you sure network interface is attached properly and we have drivers for it?" 0 0
    exit 254
fi

echo "Asking for IP using DHCP ..."
udhcpc

if [ -z "$bk_timeserver" ]; then
    echo "No timeserver specified, skipping ntpdate"
else
    echo "Adjusting time ..."
    ntpdate $bk_timeserver
fi

if [ $bk_action == "provision" ]; then
    butterknife-provision
    sync
    sleep 10
    poweroff -f
fi

while [ 1 ]; do
    action=$(dialog --no-cancel --menu "What do you want to do" 0 0 0 \
        provision       "Provision this machine" \
        advanced        "Advanced options" \
        reboot          "Reboot" \
        poweroff        "Shutdown" 2>&1 >$(tty))
        
    clear
    
    case $action in
        reboot)
            reboot -f
        ;;
        poweroff)
            poweroff -f
        ;;
        provision)
            butterknife-provision
            read -p "Press Enter to continue..."

        ;;
        advanced)
            butterknife-advanced-options
        ;;
    esac
done
