#!/bin/bash
# openbot-boat-pre-stop: installed by openbot-hosted-update. Changes to this file are replaced.
set -u

sudo -n touch /run/openbot-pre-stop || exit 1
sudo -n systemctl stop openbot-pre-stop-restart.timer 2>/dev/null
sudo -n systemd-run --quiet --collect --unit=openbot-pre-stop-restart --on-active=15min /bin/sh -c \
  'if find /run/openbot-pre-stop -mmin +5 2>/dev/null | grep -q .; then rm -f /run/openbot-pre-stop && systemctl start --no-block openbot.service; fi' ||
  echo "The start after a cancelled stop is not set." >&2
if sudo -n timeout 40 systemctl stop openbot.service; then exit 0; fi
sudo -n systemctl kill --signal=SIGKILL openbot.service
for _ in $(seq 1 10); do
  case $(systemctl show --property=ActiveState --value openbot.service) in
    inactive | failed) exit 0 ;;
  esac
  sleep 0.5
done
exit 1
