#! /bin/bash

MINIPCIE_RST_PIN=88
MINIPCIE_DIS_PIN=89

resize2fs() {
    if [ -f /sbin/expand2fs ]; then
        expand2fs
        mv /sbin/expand2fs /sbin/expand2fs.bak
	check_tpm
	check_tpm2
	sync
        /sbin/reboot -d -f -i
    fi
}

check_tpm () {
	if i2cdetect -y -r 0 0x20 0x20 | grep "\-\-" > /dev/null; then
		if ! grep "blacklist tpm" "/etc/modprobe.d/fbdev-blacklist.conf" > /dev/null; then
			echo "blacklist tpm" >> "/etc/modprobe.d/fbdev-blacklist.conf"
			echo "blacklist tpm_i2c_infineon" >> "/etc/modprobe.d/fbdev-blacklist.conf"
		fi
	else
		sed -i '/blacklist tpm/d' /etc/modprobe.d/fbdev-blacklist.conf
	fi
}

check_tpm2() {
        if [ -e "/dev/tpm0" ]; then
                sed -i '/blacklist tpm_spi_tis/d' /etc/modprobe.d/fbdev-blacklist.conf
		if systemctl status tpm2-resourcemgr.service | grep "running"; then
			systemctl enable tpm2-resourcemgr.service
                	systemctl start tpm2-resourcemgr.service
		fi
        else
		if ! grep -q "blacklist tpm_spi_tis" "/etc/modprobe.d/fbdev-blacklist.conf"; then
                        echo "blacklist tpm_spi_tis" >> "/etc/modprobe.d/fbdev-blacklist.conf"
                fi
                systemctl disable tpm2-resourcemgr.service
                systemctl stop tpm2-resourcemgr.service
        fi
}

init_cel() {
	echo $MINIPCIE_RST_PIN > /sys/class/gpio/export
	echo "out" > /sys/class/gpio/gpio${MINIPCIE_RST_PIN}/direction
	echo 0 > /sys/class/gpio/gpio${MINIPCIE_RST_PIN}/value

	echo $MINIPCIE_DIS_PIN > /sys/class/gpio/export
	echo "out" > /sys/class/gpio/gpio${MINIPCIE_DIS_PIN}/direction
	echo 0 > /sys/class/gpio/gpio${MINIPCIE_DIS_PIN}/value
}

off_led() {
        echo 0 > /sys/class/leds/uc8100me\:USB/brightness
        echo 0 > /sys/class/leds/uc8100me\:SD/brightness
        echo 0 > /sys/class/leds/uc8100me\:CEL1/brightness
        echo 0 > /sys/class/leds/uc8100me\:CEL2/brightness
        echo 0 > /sys/class/leds/uc8100me\:CEL3/brightness
	echo 0 > /sys/class/leds/uc8100me\:DIA1/brightness
	echo 0 > /sys/class/leds/uc8100me\:DIA2/brightness
	echo 0 > /sys/class/leds/uc8100me\:DIA3/brightness
}

set_uart_mode() {
	# set uart mode:RS232 as default
	setinterface /dev/ttyM0 0 >/dev/null 2>&1
	setinterface /dev/ttyM1 0 >/dev/null 2>&1
}

exec_push_btn () {
    killall -9 push_btn >/dev/null 2>&1
    /sbin/push_btn >/dev/null 2>&1 &
}

case "$1" in
    start)
		resize2fs
		init_cel
		set_uart_mode
		set_module_cfg > /dev/null 2>&1 &
		exec_push_btn
		/bin/factory_test.sh > /dev/null 2>&1 &
        ;;
    restart|reload|force-reload)
        echo "Error: argument '$1' not supported" >&2
        exit 3
        ;;
    stop)
		killall -9 chk_signal >/dev/null 2>&1
		killall -9 push_btn >/dev/null 2>&1
		cell_mgmt power_off
    		off_led
        ;;
    *)
        echo "Usage: $0 start|stop" >&2
        exit 3
        ;;
esac

