1#!/bin/bash
2
3# shellcheck disable=SC2046
4# Usage of this utility
5function usage() {
6	echo "Usage:"
7	echo "  ampere_power_util.sh mb [status|shutdown_ack|force_reset|soft_off]";
8}
9
10power_status() {
11	st=$(busctl get-property xyz.openbmc_project.State.Chassis /xyz/openbmc_project/state/chassis0 xyz.openbmc_project.State.Chassis CurrentPowerState | cut -d"." -f6)
12	if [ "$st" == "On\"" ]; then
13		echo "on"
14	else
15		echo "off"
16	fi
17}
18
19shutdown_ack() {
20	if [ -f "/run/openbmc/host@0-softpoweroff" ]; then
21		echo "Receive shutdown ACK triggered after softportoff the host."
22		touch /run/openbmc/host@0-softpoweroff-shutdown-ack
23	else
24		echo "Receive shutdown ACK triggered"
25		sleep 3
26		systemctl start obmc-chassis-poweroff@0.target
27	fi
28}
29
30soft_off() {
31	# Trigger shutdown_req
32	touch /run/openbmc/host@0-softpoweroff
33	gpioset $(gpiofind host0-shd-req-n)=0
34	sleep 1s
35	gpioset $(gpiofind host0-shd-req-n)=1
36
37	# Wait for shutdown_ack from the host in 30 seconds
38	cnt=30
39	while [ $cnt -gt 0 ];
40	do
41		# Wait for SHUTDOWN_ACK and create the host@0-softpoweroff-shutdown-ack
42		if [ -f "/run/openbmc/host@0-softpoweroff-shutdown-ack" ]; then
43			break
44		fi
45		sleep 1
46		cnt=$((cnt - 1))
47	done
48	# Softpoweroff is successful
49	sleep 2
50	rm -rf /run/openbmc/host@0-softpoweroff
51	if [ -f "/run/openbmc/host@0-softpoweroff-shutdown-ack" ]; then
52		rm -rf /run/openbmc/host@0-softpoweroff-shutdown-ack
53	fi
54	echo 0
55}
56
57force_reset() {
58	if [ -f "/run/openbmc/host@0-softpoweroff" ]; then
59		# In graceful host reset, after trigger os shutdown,
60		# the phosphor-state-manager will call force-warm-reset
61		# in this case the force_reset should wait for shutdown_ack from host
62		cnt=30
63		while [ $cnt -gt 0 ];
64		do
65			if [ -f "/run/openbmc/host@0-softpoweroff-shutdown-ack" ]; then
66				break
67			fi
68			echo "Waiting for shutdown-ack count down $cnt"
69			sleep 1
70			cnt=$((cnt - 1))
71		done
72		# The host OS is failed to shutdown
73		if [ $cnt == 0 ]; then
74			echo "Shutdown-ack time out after 30s."
75			exit 0
76		fi
77	fi
78	echo "Triggering sysreset pin"
79	gpioset $(gpiofind host0-sysreset-n)=0
80	sleep 1
81	gpioset $(gpiofind host0-sysreset-n)=1
82}
83
84if [ $# -lt 2 ]; then
85	echo "Total number of parameter=$#"
86	echo "Insufficient parameter"
87	usage;
88	exit 0;
89fi
90
91if [ "$1" != "mb" ]; then
92	echo "Invalid parameter1=$1"
93	usage;
94	exit 0;
95fi
96
97mkdir -p /run/openbmc/
98
99if [ "$2" == "shutdown_ack" ]; then
100	shutdown_ack
101elif [ "$2" == "status" ]; then
102	power_status
103elif [ "$2" == "force_reset" ]; then
104	force_reset
105elif [ "$2" == "soft_off" ]; then
106	ret=$(soft_off)
107	if [ "$ret" == 0 ]; then
108		echo "The host is already softoff"
109	else
110		echo "Failed to softoff the host"
111	fi
112	exit "$ret";
113else
114	echo "Invalid parameter2=$2"
115	usage;
116fi
117
118exit 0;
119