#!/bin/bash2

if [ -f /etc/phion/functions ]; then
	source /etc/phion/functions
	logerror="LogError box_System_phionrc"
else
	logerror=echo
fi

# hwtool needs the MAC for fingerprinting ancient hardware, so we load required modules here.
/sbin/modprobe e100
/sbin/modprobe e1000
/sbin/modprobe igb
/sbin/modprobe e1000e
/sbin/modprobe ixgbe
/sbin/modprobe 8139too
/sbin/modprobe 8139cp

MODEL=$(/opt/phion/bin/hwtool -m 2>/dev/null)
DEVMAP=$(/opt/phion/bin/hwtool -c | sed -e '2d')
DEVMAPSUB=$(/opt/phion/bin/hwtool -c | sed -e '1d')

if [ -z "$MODEL" ]; then
	/opt/phion/bin/hwtool -a 2
	$logerror "Error" "[autoinstallation-stick] No compatible appliance detected."
	$logerror "Error" "[autoinstallation-stick] Could not set initial appliance configuration."
	exit 1
fi

$logerror "Info" "[autoinstallation-stick] Detectet appliance model $MODEL"
$logerror "Info" "[autoinstallation-stick] Detectet appliance device map $DEVMAP"
$logerror "Info" "[autoinstallation-stick] Detectet appliance sub model type $DEVMAPSUB"

# copy default configurations
CONFFILES=("box" "boxnet" "bootloader" "boxadm" "boxlic") 
for CONFFILE in ${CONFFILES[@]}; do
	if [ -f /opt/phion/modules/defs/autoinstallation-stick/${CONFFILE}_${MODEL}-${DEVMAPSUB}.conf ];then
		cp -vf /opt/phion/modules/defs/autoinstallation-stick/${CONFFILE}_${MODEL}-${DEVMAPSUB}.conf /opt/phion/config/active/${CONFFILE}.conf
		$logerror "Info" "[autoinstallation-stick] Copy ${CONFFILE}_${MODEL}-${DEVMAPSUB}.conf"
	elif [ -f /opt/phion/modules/defs/autoinstallation-stick/${CONFFILE}_${MODEL}.conf ];then
		cp -vf /opt/phion/modules/defs/autoinstallation-stick/${CONFFILE}_${MODEL}.conf /opt/phion/config/active/${CONFFILE}.conf
		$logerror "Info" "[autoinstallation-stick] Copy ${CONFFILE}_${MODEL}.conf"
	elif [ -f /opt/phion/modules/defs/autoinstallation-stick/${CONFFILE}-default.conf ]; then
	   	cp -vf /opt/phion/modules/defs/autoinstallation-stick/${CONFFILE}-default.conf /opt/phion/config/active/${CONFFILE}.conf
		$logerror "Info" "[autoinstallation-stick] Copy ${CONFFILE}-default.conf"
	fi
done

exec 3<> /opt/phion/config/active/boxnet.conf && awk -v TEXT="DEVMAP = $DEVMAP\nDEVMAPSUB = $DEVMAPSUB" 'BEGIN {print TEXT}{print}' /opt/phion/config/active/boxnet.conf >&3

/opt/phion/bin/procpar -n -b
/etc/phion/bin/post_install --autoinstallation part2

# some script causes fatal log entries since acpf is not yet running.
# since nothing fatal really could have happened until now, we just delete the fatal log
rm -f /var/phion/logs/fatal.log 

$logerror "Notice" "[autoinstallation-stick] Finished appliance configuration. Now rebooting."
echo
echo Finished appliance configuration. Now rebooting ...
echo
reboot 

