#!/bin/sh
set -eu

online_since=0
while :; do
    if state=$(upsc h1000m@127.0.0.1 ups.status 2>/dev/null); then
        case " $state " in
            *' FSD '*)
                case " $state " in
                    *' OL '*)
                        read -r uptime _ </proc/uptime
                        now=${uptime%%.*}
                        [ "$online_since" -ne 0 ] || online_since=$now
                        if [ "$((now-online_since))" -ge 120 ]; then
                            # upsd latches FSD. Restart it only after a stable return to mains.
                            /etc/init.d/nut-server restart
                            online_since=0
                        fi
                        ;;
                    *) online_since=0 ;;
                esac
                ;;
            *)
                online_since=0
                case " $state " in
                    *' OB '*) case " $state " in
                        *' LB '*)
                            password=$(uci -q get nut_server.lanups_policy.password)
                            if { printf 'USERNAME lanups_policy\nPASSWORD %s\nFSD h1000m\n' "$password"; sleep 1; } |
                                timeout 5 nc 127.0.0.1 3493 | grep -q '^OK FSD-SET'; then
                                logger -t lanups-fsd 'Published FSD after on-battery and low-battery status'
                            fi
                            ;;
                    esac ;;
                esac
                ;;
        esac
    else
        online_since=0
    fi
    sleep 3
done
