1#!/bin/bash
2# Copyright 2021 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#      http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16source /usr/share/gpio-host-pwr/lib.sh || exit
17
18gpio_build_cache 10 "$HOST_GPIO_PGOOD" "$HOST_GPIO_PWR_BTN" || exit
19gpio_init "$HOST_GPIO_PGOOD" || exit
20
21# Set the power status LED
22if [ -n "$HOST_LED_PWR" ]; then
23  echo 'none' > /sys/class/leds/"$HOST_LED_PWR"/trigger || true
24  echo '0' > /sys/class/leds/"$HOST_LED_PWR"/brightness || true
25fi
26
27# Ensure the watchdog is no longer going to run
28host_pwr_stop_watchdog || true
29
30# We don't want to do anything if the machine is already off
31pgood="$(gpio_get_value "$HOST_GPIO_PGOOD")" || exit
32if (( pgood == 0 )); then
33  echo 'Host is already off, doing nothing' >&2
34  exit 0
35fi
36
37# Do a long push of the button if PGOOD
38echo 'Stopping host power' >&2
39rc=0
40gpio_set_value "$HOST_GPIO_PWR_BTN" 1 || rc=$?
41
42# Loop until we realize that host power is off
43# Limit the loop count to 10 seconds as we should never
44# have to wait this long for poweroff
45s=$SECONDS
46while true; do
47  if ! pgood="$(gpio_get_value "$HOST_GPIO_PGOOD")"; then
48    rc=1
49    break
50  fi
51  if (( pgood == 0 )); then
52    echo 'Host is now off' >&2
53    break
54  fi
55  if (( SECONDS - s > 10 )); then
56    echo 'Poweroff timed out, terminating' >&2
57    rc=2
58    break
59  fi
60  sleep 0.1
61done
62
63gpio_set_value "$HOST_GPIO_PWR_BTN" 0 || rc=$?
64
65exit $rc
66