#!/bin/bash
#
# Copyright (C) 2023 MOXA Inc. All rights reserved.
# This software is distributed under the terms of the MOXA SOFTWARE NOTICE.
# See the file LICENSE for details.
#
# Authors:
#       2022    Wilson Huang <WilsonYS.Huang@moxa.com>
#
# Description:
#	Moxa power ignition daemon
#

DMIDECODE="/usr/sbin/dmidecode"
SHUTDOWN="/usr/sbin/shutdown"

_product_V2403C() {
	POWER_IGT_GPIO="85"
	POWER_IGT_SIG_OFF_VAL="0"
	POWER_IGT_DELAY_SEC="1"
}

declare -A PRODUCT_PROFILE=(
	["V2403C"]=_product_V2403C
)

is_module_loaded() {
	local mod_name=$1
	if lsmod | grep -w $mod_name &> /dev/null; then
		return 0
	else
		return 1
	fi
}


load_product_name_from_dmi() {
	local ret=1

	for m in $($DMIDECODE -t 12 | grep "Option " | awk -F ':' '{print substr($2,1,11)}' | sed 's/ //g');
	do
		if [[ ${PRODUCT_PROFILE[$m]} ]]; then
			TARGET_PRODUCT=$m
			${PRODUCT_PROFILE[$TARGET_PRODUCT]}
			ret=0
			break
		fi
	done

	return $ret
}

load_product_name_from_file() {
	echo "TBD"
}

# gpio
gpc() {
	local gpio=$1
	local GPIO_TABLE=(
		10 11 12 13 14 15 16 17
		20 21 22 23 24 25 26 27
		30 31 32 33 34 35 36 37
		40 41 42 43 44 45 46 47
		50 51 52 53 54 55 56 57
		60 61 62 63 64 65 66 67
		70 71 72 73 74 75 76 77
		80 81 82 83 84 85 86 87
		90 91 92 93 94 95 96 97
                100 101 102 103 104 105
	)

	if ! $(is_module_loaded gpio_it87); then
		echo "gpio_it87 driver is not loaded."
		exit 1
	fi

	[[ ! ${GPIO_TABLE[*]} =~ $gpio ]] && \
			echo "Invalid gpio number." && exit 1

	for gpiochip in /sys/class/gpio/gpiochip*
	do
		if cat "${gpiochip}"/label | grep -q "gpio_it87"
		then
			base=$(cat "${gpiochip}"/base)
			break
		fi
	done

	group=$(($gpio / 10 - 1))
	bit=$(($gpio % 10))
	echo $((base + 8 * group + bit))
}

gpio_request() {
	local gpio=${1}

	if [ ! -e "/sys/class/gpio/gpio${gpio}" ]
	then
		echo "${gpio}" > /sys/class/gpio/export
	fi
}

gpio_get_value() {
	local gpio=${1}

	gpio_request "${gpio}"
	cat "/sys/class/gpio/gpio${gpio}/value"
}

main() {
	load_product_name_from_dmi
	gpio_pin=$(gpc $POWER_IGT_GPIO)

	while true
	do
		igt_state=$(gpio_get_value $gpio_pin)

		if [[ $igt_state == $POWER_IGT_SIG_OFF_VAL ]]; then
			wall -n "Power igition input signal is off. The system is going down now."
			$SHUTDOWN -h now
			exit 0
		fi

		sleep $POWER_IGT_DELAY_SEC
	done
}

main