#!/bin/sh

set -e

getcmdline() {
	cat /proc/cmdline
}

# getarg functions copied from dracut-lib.sh

getarg() {
    local _o _val _doecho
    unset _val
    unset _o
    unset _doecho
    CMDLINE=$(getcmdline)

    for _o in $CMDLINE; do
        if [ "${_o%%=*}" = "${1%%=*}" ]; then
            if [ -n "${1#*=}" -a "${1#*=*}" != "${1}" ]; then
                # if $1 has a "=<value>", we want the exact match
                if [ "$_o" = "$1" ]; then
                    _val="1";
                    unset _doecho
                fi
                continue
            fi

            if [ "${_o#*=}" = "$_o" ]; then
                # if cmdline argument has no "=<value>", we assume "=1"
                _val="1";
                unset _doecho
                continue
            fi

            _val="${_o#*=}"
            _doecho=1
        fi
    done
    if [ -n "$_val" ]; then
        [ "x$_doecho" != "x" ] && echo "$_val";
        return 0;
    fi
    return 1;
}

getargbool() {
    local _b
    unset _b
    local _default
    _default="$1"; shift
    _b=$(getarg "$@")
    [ $? -ne 0 -a -z "$_b" ] && _b="$_default"
    if [ -n "$_b" ]; then
        [ $_b = "0" ] && return 1
        [ $_b = "no" ] && return 1
        [ $_b = "off" ] && return 1
    fi
    return 0
}

phionks(){
	
	# crypt argutement will be set in loader/phion.c
	# / and /phion0 will be encrypted whereas /art must not be encrypted due to ART rescue installation
	# but configuration archive will be stored encrypted on /art partition
	# in rescue installation ${CRYPTARG} can not be used. encrypted partitions will still be encrypted, non-encrypted will stay non-encrypted
	# no way to change that with anaconda!
	local CRYPTARG=""
	local KSFILE="/run/install/ks.cfg"

	if getargbool 0 'crypt'; then
		CRYPTARG=" --encrypted --passphrase=$(/opt/phion/bin/unlinkserial)"
	fi
	
	if [ -f $KSFILE ]; then # replace #CRYPT with crypt string
		sed -i -e "s/#CRYPT/${CRYPTARG}/" "$KSFILE"
	fi
	
	if ! getargbool 0 'autoappl' && ! getarg 'genericappl'; then
		return 0
	fi

	local MODEL="$(/opt/phion/bin/hwtool -m 2>/dev/null || echo "")"
	local RESCUE="$(getargbool 0 'art' && echo 1)"
	local GENERIC="$(getarg 'genericappl=')"

	# Do we have an "appl" like installation?
	if [ ! _$GENERIC = _ ]; then
		GENKSFILE=""
		case "$GENERIC" in
			box|boxusb)
				GENKSFILE="/opt/phion/appmodels/ks-box-generic.cfg"
				;;
			mc|cc|mcusb|ccusb)
				GENKSFILE="/opt/phion/appmodels/ks-mc-generic.cfg"
				;;
			*)
				echo "wrong option for genericappl: $GENERIC"
				exit 1
				;;
		esac

		cat "$GENKSFILE" > $KSFILE
		sed -i -e "s/#CRYPT/${CRYPTARG}/" "$KSFILE"
		exit 0
	fi

	# If we get here we should have a model.
	if [ _$MODEL = _ ]; then
		echo  "No model for phion-installer"
		exit 1
	fi

	# Rescue Kickstart
	if [ _$RESCUE = _1 ]; then
		cat /opt/phion/appmodels/ks-head.cfg > $KSFILE

		BOOTP=$(findfs LABEL=/boot)
		ARTP=$(findfs LABEL=/art)
		ROOTP=$(findfs LABEL=/)
		# encrypted root/phion0 partitions don't have set a label. ART "reinstall" binary will tell us via kernel command line
		[ -z "${ROOTP}" ] && ROOTP=$(getarg 'artroot=')
		PHION0P=$(findfs LABEL=/phion0)
		# encrypted root/phion0 partitions don't have set a label. ART "reinstall" binary will tell us via kernel command line
		[ -z "${PHION0P}" ] && PHION0P=$(getarg 'artphion0=')

		# Swap device Label is composed of SWAP-\${devname}, so we have to get it with blkid
		SWAPDEV=$(blkid | awk '/LABEL="SWAP/ { print $1; }')
		# Strip trailing colon
		SWAPP=${SWAPDEV%:}

		# encrypted swap partition don't have set a label. ART "reinstall" binary will tell us via kernel command line
		if getarg 'artswap'; then
			[ -z "${SWAPP}" ] && SWAPP=$(getarg 'artswap=')
		fi

		if [ -z "${SWAPP}" ]; then
			# If swap device was not found via label, check for type
			# anaconda may introduce zram if not sufficient RAM, ignore it
			SWAPDEV=$(blkid -t TYPE=swap | grep -v '^/dev/zram' | awk '{ print $1; }')
			# Strip trailing colon
			SWAPP=${SWAPDEV%:}
		fi

		REPODEV="$(getarg 'inst.repo=')"
		STRIPEDDEV="${REPODEV#hd:}"
		STRIPEDDEV="${STRIPEDDEV%:*}"
		
		[ "${STRIPEDDEV%[0-9]}" != "sr" ] &&
			echo "harddrive --partition=/dev/${STRIPEDDEV} --dir=/" >> $KSFILE

		case "$MODEL" in
			F12|F18|F18b|F80|F80b|F82|F82b|F93|F180|F180b|F180R|F183|F183R|F193|F280|F280b|F280c|F380|F380b|F400b|F400c|F600c|F600d|F800b|F800c|F900b|F1000|C610)
				echo "
				shutdownbehaviour --action=reboot
				bootloader --location=mbr --driveorder=/dev/disk/phion/phb,/dev/disk/phion/pha
			
				part /boot --label /boot --fstype ext4 --onpart=${BOOTP} --noformat
				part / --label / --fstype ext4 --onpart=${ROOTP}
				part /phion0 --label /phion0 --fstype ext4 --onpart=${PHION0P}
				part swap --fstype swap --onpart=${SWAPP}
				" >> $KSFILE
				if [ ! -z ${ARTP} ]; then
					echo "part /art --label /art --fstype ext4 --onpart=${ARTP} --noformat

				" >> $KSFILE
				fi
				;;
			F900|C400)
				echo "
				shutdownbehaviour --action=reboot
				bootloader --location=mbr --driveorder=/dev/disk/phion/phc,/dev/disk/phion/phb,/dev/disk/phion/pha
				
				part /boot --label /boot --fstype ext4 --onpart=${BOOTP} --noformat 
				part / --label / --fstype ext4 --onpart=${ROOTP}
				part /phion0 --label /phion0 --fstype ext4 --onpart=${PHION0P}
				part swap --fstype swap --onpart=${SWAPP}
				" >> $KSFILE
				if [ ! -z ${ARTP} ]; then
					echo "part /art --label /art --fstype ext4 --onpart=${ARTP} --noformat

				" >> $KSFILE
				fi
				;;
			*)
				echo "
				shutdownbehaviour --action=reboot
				bootloader --location=mbr
				
				part /boot --label /boot --fstype ext4 --onpart=${BOOTP} --noformat 
				part / --label / --fstype ext4 --onpart=${ROOTP}
				part /phion0 --label /phion0 --fstype ext4 --onpart=${PHION0P}
				part swap --fstype swap --onpart=${SWAPP}
				" >> $KSFILE
				if [ ! -z ${ARTP} ]; then
					echo "part /art --label /art --fstype ext4 --onpart=${ARTP} --noformat

				" >> $KSFILE
				fi
				;;
		esac

		# Package selection
		case "$MODEL" in
			PH-MC|C400|C610)
				echo -e "\n%packages\n@base\n@core\n@boxmc\n@mc\n%end\n" >> $KSFILE
				;;
			*)
				echo -e "\n%packages\n@base\n@core\n%end\n" >> $KSFILE
				;;
		esac		

		# TODO
		# Post install
		echo "
%post --nochroot
# copy default configuration config files to the installed system
# create a script to run in the chroot
cat<<EFF>>/mnt/sysimage/tmp/anaconda-post.sh
#!/bin/sh

mkdir -p /var/phion/packages/tgz
cd /var/phion/packages

# Mount ART partition where config, iso and utils reside
if [ ${STRIPEDDEV} ]; then
	mount /dev/${STRIPEDDEV} /mnt
else
	mount ${ARTP} /mnt
fi

# Install available patches
echo "0" > /tmp/packageinstallation
if [ -d /mnt/appliance/patches ]; then
	for a in \\\$(ls /mnt/appliance/patches/*.tgz); do
		echo "\\\$a"
		cd /var/phion/packages/tgz
		tar -xvzf \\\$a
		./doit
		[[ \\\$? -ne 0 ]] && echo "1" > /tmp/packageinstallation
		rm -rf /var/phion/packages/tgz/*
	done
fi

# Install available hotfixes
if [ -d /mnt/appliance/hotfixes ]; then
	for b in \\\$(ls /mnt/appliance/hotfixes/*.tgz); do
		echo "\\\$b"
		cd /var/phion/packages/tgz
		tar -xvzf \\\$b
		./doit
		[[ \\\$? -ne 0 ]] && echo "1" > /tmp/packageinstallation
		rm -rf /var/phion/packages/tgz/*
	done
fi

# copy config
cp -f /mnt/*.conf /opt/phion/config/active/

# Copy PAR
if [ -e /mnt/box.par ]; then
	cp -f /mnt/box.par /opt/phion/update/
fi

if [ -e /mnt/box.pgz ]; then
	zcat /mnt/box.pgz > /opt/phion/update/box.par
fi

if [ -e /mnt/box.pca ]; then
	cp -f /mnt/box.pca /opt/phion/update/
fi

umount /mnt

# phion post install - this should be common in all installations.
/bin/touch /etc/phion/INSTALL
/bin/touch /var/run/watchdog.state.service
cd /etc/phion/bin
/opt/phion/bin/procpar -n -b
exec ./post_install
EFF
# actually run the script chrooted, save the log
chmod 766 /mnt/sysimage/tmp/anaconda-post.sh
/mnt/sysimage/usr/sbin/chroot /mnt/sysimage /tmp/anaconda-post.sh 1>/mnt/sysimage/root/post_install.log 2>&1

# touch /mnt/sysimage/opt/phion/preserve/FIRSTBOOT

# clean up
rm -rf /mnt/sysimage/tmp/anaconda-post.sh
rm -rf /mnt/sysimage/tmp/phionlcd?

# set status LED
if [[ \$(cat /mnt/sysimage/tmp/packageinstallation) = 1 ]]; then
	# red, solid
	/mnt/sysimage/opt/phion/bin/hwtool -l 1
else
	# green, solid
	/mnt/sysimage/opt/phion/bin/hwtool -l 7
fi
rm -f /mnt/sysimage/tmp/packageinstallation

# ring the bell
/opt/phion/bin/hwtool -a 1

# give ledd daemon time to do it's job
sleep 1

%end
		" >> $KSFILE
		
	# Normal Kickstart generation
	else
		
		# Generate kickstart file header
		cat /opt/phion/appmodels/ks-head.cfg > $KSFILE

		# Partitioning scheme
		case $MODEL in
			F12|F18|F18b)
				echo "
				shutdownbehaviour --action=halt
				bootloader --location=mbr

				clearpart --all --initlabel --drives=/dev/disk/phion/pha
				part / --label / --fstype ext4 --size 8192 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				part /boot --label /boot --fstype ext4 --size 1024 --ondisk=/dev/disk/phion/pha
				part /art --label /art --fstype ext4 --size 3072 --ondisk=/dev/disk/phion/pha
				part /phion0 --label /phion0 --fstype ext4 --size 4096 --ondisk=/dev/disk/phion/pha ${CRYPTARG} --grow
				part swap --label swap --fstype swap --size 2048 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				" >> $KSFILE
				;;
				
			F80|F80b|F82|F82b|F93|F180|F180b|F180R|F183|F183R|F193|F280|F280b|F280c|F380|F380b|F400b|F400c)
				echo "
				shutdownbehaviour --action=halt
				bootloader --location=mbr

				clearpart --all --initlabel --drives=/dev/disk/phion/pha
				part / --label / --fstype ext4 --size 8192 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				part /boot --label /boot --fstype ext4 --size 1024 --ondisk=/dev/disk/phion/pha
				part /art --label /art --fstype ext4 --size 3072 --ondisk=/dev/disk/phion/pha
				part /phion0 --label /phion0 --fstype ext4 --size 4096 --ondisk=/dev/disk/phion/pha ${CRYPTARG} --grow
				part swap --label swap --fstype swap --size 4096 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				" >> $KSFILE
				;;
				
			F600c|F600d|F800b)
				echo "
				shutdownbehaviour --action=halt
				bootloader --location=mbr

				clearpart --all --initlabel --drives=/dev/disk/phion/pha
				part / --label / --fstype ext4 --size 8192 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				part /boot --label /boot --fstype ext4 --size 1024 --ondisk=/dev/disk/phion/pha
				part /art --label /art --fstype ext4 --size 3072 --ondisk=/dev/disk/phion/pha
				part /phion0 --label /phion0 --fstype ext4 --size 4096 --ondisk=/dev/disk/phion/pha ${CRYPTARG} --grow
				part swap --label swap --fstype swap --size 8192 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				" >> $KSFILE
				;;
				
			F800c)
				echo "
				shutdownbehaviour --action=halt
				bootloader --location=mbr

				clearpart --all --initlabel --drives=/dev/disk/phion/pha
				part / --label / --fstype ext4 --size 8192 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				part /boot --label /boot --fstype ext4 --size 1024 --ondisk=/dev/disk/phion/pha
				part /art --label /art --fstype ext4 --size 3072 --ondisk=/dev/disk/phion/pha
				part /phion0 --label /phion0 --fstype ext4 --size 4096 --ondisk=/dev/disk/phion/pha ${CRYPTARG} --grow
				part swap --label swap --fstype swap --size 12288 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				" >> $KSFILE
				;;
				
			F900)
				echo "
				shutdownbehaviour --action=halt
				bootloader --location=mbr

				clearpart --all --initlabel --drives=/dev/disk/phion/pha,/dev/disk/phion/phb,/dev/disk/phion/phc
				part / --label / --fstype ext4 --size 8192 --ondisk=/dev/disk/phion/phb ${CRYPTARG} --grow
				part /boot --label /boot --fstype ext4 --size 512 --ondisk=/dev/disk/phion/phb
				part /art --label /art --fstype ext4 --size 3072 --ondisk=/dev/disk/phion/phb
				part /phion0 --label /phion0 --fstype ext4 --size 4096 --ondisk=/dev/disk/phion/phc ${CRYPTARG} --grow
				part swap --label swap --fstype swap --size 12288 --ondisk=/dev/disk/phion/phb ${CRYPTARG}
				" >> $KSFILE
				;;
				
			F900b)
				echo "
				shutdownbehaviour --action=halt
				bootloader --location=mbr

				clearpart --all --initlabel --drives=/dev/disk/phion/pha
				part / --label / --fstype ext4 --size 8192 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				part /boot --label /boot --fstype ext4 --size 1024 --ondisk=/dev/disk/phion/pha
				part /art --label /art --fstype ext4 --size 3072 --ondisk=/dev/disk/phion/pha
				part /phion0 --label /phion0 --fstype ext4 --size 4096 --ondisk=/dev/disk/phion/pha ${CRYPTARG} --grow
				part swap --label swap --fstype swap --size 16384 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				" >> $KSFILE
				;;
			
			F1000)
				echo "
				shutdownbehaviour --action=halt
				bootloader --location=mbr

				clearpart --all --initlabel --drives=/dev/disk/phion/pha
				part / --label / --fstype ext4 --size 8192 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				part /boot --label /boot --fstype ext4 --size 1024 --ondisk=/dev/disk/phion/pha
				part /art --label /art --fstype ext4 --size 3072 --ondisk=/dev/disk/phion/pha
				part /phion0 --label /phion0 --fstype ext4 --size 4096 --ondisk=/dev/disk/phion/pha ${CRYPTARG} --grow
				part swap --label swap --fstype swap --size 32768 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				" >> $KSFILE
				;;
				
			C400)
				echo "
				shutdownbehaviour --action=halt
				bootloader --location=mbr --driveorder=/dev/disk/phion/phc,/dev/disk/phion/phb,/dev/disk/phion/pha

				clearpart --all --initlabel --drives=/dev/disk/phion/pha,/dev/disk/phion/phb,/dev/disk/phion/phc
				part / --label / --fstype ext4 --size 10240 --ondisk=/dev/disk/phion/phb ${CRYPTARG} --grow
				part /boot --label /boot --fstype ext4 --size 1024 --ondisk=/dev/disk/phion/phc --grow
				part /art --label /art --fstype ext4 --size 10240 --ondisk=/dev/disk/phion/phb
				part /phion0 --label /phion0 --fstype ext4 --size 4096 --ondisk=/dev/disk/phion/pha ${CRYPTARG} --grow
				part swap --label swap --fstype swap --size 4096 --ondisk=/dev/disk/phion/phb ${CRYPTARG}
				" >> $KSFILE
				;;
				
			C610)
				echo "
				shutdownbehaviour --action=halt
				bootloader --location=mbr

				clearpart --all --initlabel --drives=/dev/disk/phion/pha,/dev/disk/phion/phb
				part / --label / --fstype ext4 --size 10240 --ondisk=/dev/disk/phion/phb ${CRYPTARG}
				part /boot --label /boot --fstype ext4 --size 1024 --ondisk=/dev/disk/phion/pha --grow
				part /art --label /art --fstype ext4 --size 10240 --ondisk=/dev/disk/phion/phb
				part /phion0 --label /phion0 --fstype ext4 --size 4096 --ondisk=/dev/disk/phion/phb ${CRYPTARG} --grow
				part swap --label swap --fstype swap --size 8192 --ondisk=/dev/disk/phion/phb ${CRYPTARG}
				" >> $KSFILE
				;;

			*) # virtual appliances
				echo "
				shutdownbehaviour --action=poweroff
				bootloader --location=mbr

				clearpart --all --initlabel --drives=/dev/disk/phion/pha
				part / --label / --fstype ext4 --size 8192 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				part /boot --label /boot --fstype ext4 --size 1024 --ondisk=/dev/disk/phion/pha
				part /art --label /art --fstype ext4 --size 3072 --ondisk=/dev/disk/phion/pha
				part /phion0 --label /phion0 --fstype ext4 --size 4096 --ondisk=/dev/disk/phion/pha ${CRYPTARG} --grow
				part swap --label swap --fstype swap --size 2048 --ondisk=/dev/disk/phion/pha ${CRYPTARG}
				" >> $KSFILE
				;;
		esac

		# Package selection
		case "$MODEL" in
			C400|C610)
				echo -e "\n%packages\n@base\n@core\n@boxmc\n@mc\n%end\n" >> $KSFILE
				;;
			*)
				echo -e "\n%packages\n@base\n@core\n%end\n" >> $KSFILE
				;;
		esac		

		# TODO
		# Post install
		echo "
%post --nochroot --log=/mnt/sysimage/root/post-ks.log
		" >> $KSFILE
		
		case "$MODEL" in
			F900)
				echo "

# create boot partition on flash device
/usr/sbin/parted --script /dev/sda \
    mklabel msdos \
    mkpart primary ext4 1MB 100% \
    set 1 boot on
sync
while [ ! -e \"/dev/sda1\" ]; do sleep 1; done
mkfs.ext4 /dev/sda1
sync

# mount boot partition and install grub
mkdir /mnt/grubChainLoader
mount -t ext4 /dev/sda1 /mnt/grubChainLoader
grub2-install --boot-directory=/mnt/grubChainLoader /dev/sda

# write grub configuration
cat > /mnt/grubChainLoader/grub2/grub.cfg <<EOL
set timeout=0

menuentry \"CloudGen Firewall on PHB\" {
	search --no-floppy --set root --label /boot
	drivemap -s hd0 \${root}
	chainloader (hd0)+1
}
EOL

# unmount and cleanup
umount /mnt/grubChainLoader
rm -rf /mnt/grubChainLoader

				" >> $KSFILE
				;;
		esac

		echo "
# phion post install - this should be common in all installations.
touch /mnt/sysimage/etc/phion/INSTALL
touch /mnt/sysimage/var/run/watchdog.state.service

# trigger autoinstallation-stick (in phionrc) in next boot
mkdir -p /mnt/sysimage/opt/phion/preserve
/bin/touch /mnt/sysimage/opt/phion/preserve/autoinstallation-stick.firstboot

# Bind-mount USB flash device where config, iso and utils reside
mount --bind /run/install/isodir /mnt/sysimage/mnt

# copy default configuration config files to the installed system
# create a script to run in the chroot
cat<<EFF>>/mnt/sysimage/tmp/anaconda-post.sh
#!/bin/sh

cd /etc/phion/bin
./post_install --autoinstallation part1

mkdir -p /var/phion/packages/tgz
cd /var/phion/packages

# Install available patches
echo "0" > /tmp/packageinstallation
if [ -d /mnt/appliance/patches ]; then
	for a in \\\$(ls /mnt/appliance/patches/*.tgz); do
		echo "\\\$a"
		cd /var/phion/packages/tgz
		tar -xvzf \\\$a
		./doit
		[[ \\\$? -ne 0 ]] && echo "1" > /tmp/packageinstallation
		rm -rf /var/phion/packages/tgz/*
	done
fi

# Install available hotfixes
if [ -d /mnt/appliance/hotfixes ]; then
	for b in \\\$(ls /mnt/appliance/hotfixes/*.tgz); do
		echo "\\\$b"
		cd /var/phion/packages/tgz
		tar -xvzf \\\$b
		./doit
		[[ \\\$? -ne 0 ]] && echo "1" > /tmp/packageinstallation
		rm -rf /var/phion/packages/tgz/*
	done
fi
EFF

# actually run the script chrooted, save the log
chmod 766 /mnt/sysimage/tmp/anaconda-post.sh
/mnt/sysimage/usr/sbin/chroot /mnt/sysimage /tmp/anaconda-post.sh 1>/mnt/sysimage/root/post_install.log 2>&1

/bin/cp -fv /mnt/install/isodir/*.iso /mnt/sysimage/art/

umount /mnt/sysimage/mnt

# create state file for ART tree creation
# touch /mnt/sysimage/opt/phion/preserve/FIRSTBOOT

# clean up
rm -rf /mnt/sysimage/tmp/anaconda-post.sh
rm -rf /mnt/sysimage/tmp/phionlcd?

# set status LED
if [[ \$(cat /mnt/sysimage/tmp/packageinstallation) = 1 ]]; then
	# red, solid
	/mnt/sysimage/opt/phion/bin/hwtool -l 1
else
	# green, solid
	/mnt/sysimage/opt/phion/bin/hwtool -l 7
fi
rm -f /mnt/sysimage/tmp/packageinstallation

# ring the bell
/opt/phion/bin/hwtool -a 1

# give ledd daemon time to do it's job
sleep 1

%end
		" >> $KSFILE
	fi
}

lcd4linux() {
	MODEL="$(/opt/phion/bin/hwtool -m 2>/dev/null || echo "Unknown")"
	CONFFILE="/opt/phion/appmodels/lcd/lcd4linux_${MODEL}.conf"

	echo "Model:" > /tmp/phionlcd1
	echo "$MODEL" >/tmp/phionlcd2

	if [ -e "$CONFFILE" ]; then
		cp "$CONFFILE" "/etc/lcd4linux.conf"
		chmod 0600 "/etc/lcd4linux.conf"
		/usr/bin/lcd4linux &
	fi
}

phionks
lcd4linux

