#!/bin/bash
#
# VERSION=15
# CHANGES="enhance the permlog feature"

source /usr/fallback/helper

function log {
	echo "[finish_production] ${1}"
	permlog "production" "[finish_production]" "${1}" ${2}
}

BEROCONF=/usr/fallback/beroconf

case "${1}" in
	start)
		# leave if card is already produced or not reproduced (remove this script too)
		NEED_PROD=$(${BEROCONF} get root need_prod | grep -v failed)
		if [ "${NEED_PROD}" != 1 ]; then
			/bin/mount -oremount,rw /
			rm -f /etc/init.d/S99finishprod
			/bin/mount -oremount,ro /
			${BEROCONF} delete root need_prod
			exit 0
		fi

		log "Logfile of 2nd stage of production-process" 1
		log "=========================================="

		# wuerg-around for ttyS0-mystery on 6400-cards
		crdtype=$(expr match "$(cat /proc/cmdline)" ".*[0-9]*-\(64\)-[0-9]\{10\}.*")
		if [ "${crdtype}" = "64" ]; then
			if [ -c /dev/ttyS0 ]; then
				log "   => Found beroNet VoIP Gateway 6400 (Fixing ttyS0 bug, rebooting.)"
				mount -oremount,rw /
				mv /dev/ttyS0 /dev/disabled_ttyS0
				mount -oremount,ro /
				reboot
				exit 1
			fi
		fi

		# check if IP-address comes from a dhcp, reboot if it's standard 10.0.0.2
		test_ip=$(expr match "$(/sbin/ifconfig eth0)" ".*inet addr:\([0-9\.]*\)")
		if [ "${test_ip}" = "10.0.0.2" ]; then
			log "   => Failed. (Couldn't retrieve address from DHCP, rebooting.)"
			reboot
			exit 1
		fi

		log " * Finishing production process: "

		# retrieve card information
		CARD_INFO=$(cat /proc/cmdline)
		CARD_UUID=$(expr match "${CARD_INFO}" ".*carduuid=\([0-9]*\-[0-9]\{2\}\-[0-9]\{10\}\)")

		# check if UUID is valid
		if [ -z "${CARD_UUID}" ]; then
			log "   => Failed. (UUID is invalid.)"
			exit 1
		fi

		# install pre-installed appfs
		mount -oremount,rw /usr/local
		chown -R root:root /usr/local/*
		[ -x /usr/local/setup/post_install.sh ] && /usr/local/setup/post_install.sh
		sleep 1; sync; sync; sleep 1
		cd / && mount -oremount,o /usr/local

		# retrieve further card information
		if [ ! -f "/usr/local/FILENAME" ]; then
			log "   => Failed. (AppFS version file not found, rebooting.)"
			reboot
			exit 1
		fi

		# set mtd1
		/bin/mount -o remount,rw /
		/bin/mknod /dev/mtd1 c 90 2 &>/dev/null

		# reproduced
		IS_REPRODUCED=0
		if /usr/fallback/fw_printenv | /bin/grep reproduced &>/dev/null; then
			log " * Reproducing mechanism"
			echo "root:$(/usr/fallback/fw_printenv | /bin/grep password | /usr/bin/cut -d '=' -f 2):10933:0:99999:7:::" > /tmp/shadow
			/bin/cat /etc/shadow | /bin/grep -v root >> /tmp/shadow
			if /bin/mv /tmp/shadow /etc/shadow &>/dev/null; then
				IS_REPRODUCED=1
				/usr/fallback/fw_setenv password
				/usr/fallback/fw_setenv reproduced
				${BEROCONF} set root reproduce-succeeded REPRODUCE_SUCCEEDED
			else
				## should not happen
				log "  => Failed. (Restoring password from u-boot)"
				${BEROCONF} set root reproduce-failed REPRODUCE_SUCCEDED_WITH_PASSWORD_ISSUE
			fi
		# produced
		else
			log " * Producing mechanism"
			APP_INFO=$(cat /usr/local/FILENAME)
			MAC_INFO=$(/sbin/ifconfig eth0 | grep HWaddr)

			CARD_REV=$(expr match "${CARD_INFO}" ".*revision=\([1-9]\{1,2\}\.[0-9]\{2\}\)")
			CARD_MAC=$(expr match "${MAC_INFO}" ".*\(\([0-9A-F]\{2\}\:\)\{5\}\([0-9A-F]\{2\}\)\)")
			CARD_APP=$(expr match "${APP_INFO}" ".*appfs\-\([a-z0-9\.\_\-]*\)\.tar\.gz")

			# check if production-system is here
			ping -c 1 prodadmin.intern.beronet.com &> /dev/null
			if [ ${?} -ne 0 ]; then
				log "   => Failed. (The production-server was not reachable, rebooting.)"
				reboot
				exit 1
			fi

			# tell production system we're done
			prod_url="http://prodadmin.intern.beronet.com/produce_setstatus.php?uuid=${CARD_UUID}&revision=${CARD_REV}&appfs=${CARD_APP}&mac=${CARD_MAC}"
			prod_res=$(wget "${prod_url}" -q -O -)

			# evaluate the reaction of the production server
			echo "${prod_res}" | grep "confirmed" &> /dev/null
			if [ ${?} -ne 0 ]; then
				log "   => Failed. (The result of production-server was not \"confirmed\", rebooting.)"
				reboot
				exit 1
			fi

			# get new password from response
			pass_new=$(expr match "${prod_res}" ".*password:\(.*\)")
			if [ -z "${pass_new}" ]; then
				log "   => Failed. (Could not retrieve a new root-password, rebooting.)"
				reboot
				exit 1
			fi

			# set new password
			/usr/local/sbin/pwchange.sh root ${pass_new}
			if [ ${?} -ne 0 ]; then
				log "   => Failed. (Could not update root-password, rebooting.)"
				reboot
				exit 1
			fi
		fi

		# unset mtd1
		/bin/rm -f /dev/mtd1
		/bin/mount -o remount,ro /

		# set default values in root.db
		${BEROCONF} delete root lan-ipaddr
		${BEROCONF} delete root lan-netmask
		${BEROCONF} delete root lan-gateway
		${BEROCONF} set root lan-dhcp 1

		if [ -z "$(${BEROCONF} get root lan-nameserver | grep -v failed)" ]; then
			${BEROCONF} set root lan-nameserver "8.8.8.8\;8.8.4.4"
		fi

		if [ -z "$(${BEROCONF} get root ntphost | grep -v failed)" ]; then
			${BEROCONF} set root ntphost pool.ntp.org
		fi

		${BEROCONF} set root beroAvahi-enabled 1
		${BEROCONF} delete root need_prod
		rm -f /usr/conf/ari.db

		# load berofix-driver and turn on all leds
		if [ -z "$(/sbin/lsmod | grep berofix_driver)" ]; then
			insmod /lib/modules/berofix-driver.ko no_detection=1
		fi
		echo 5 > /sys/class/beronet/gateway/led_program

		# configure api-user
		/usr/local/php/apiusers.php admin

		# if reproduced, start app script
		if [ "${IS_REPRODUCED}" = "1" ]; then
			log " * Reproduced: rexecuting S90app script"
			/etc/init.d/S90app start
		fi

		log "   => Done."
		exit 0
		;;
	stop)
		exit 0
		;;
	*)
		echo "Usage: ${0} {start}" >&2
		exit 1
		;;
esac
