#!/bin/bash

print_usage() {
  cat <<"EOF"
Switch back to the installation pane with 'C-b l'.
Press 'C-b l' again to come back here.
When installation is halted, type 'stop -c' to continue.
EOF
}

print_help() {
  cat <<"EOF"
USAGE:
    stop [option]
    Interrupt the installation for debugging purposes.
    When invoked without options, the installation is halted
    at the end, just before the reboot.
OPTIONS:
    -c, --continue
      Resume installation. This may trigger a reboot.
    -p, --pause, --now
      Halt as soon as possible.
SEE ALSO:
    check_install
EOF
}

if [[ $1 = "-h" || $1 = "--help" ]]; then
  print_help
elif [[ $1 = "-c" || $1 = "--continue" ]]; then
  pid=$(ps --no-headers $(pidof sleep) | sed -n -E 's/^\s*\b([0-9]+)\b.*\bsleep inf$/\1/p' | tr '\n' ' ')
  if [[ $pid ]]; then
    pid=${pid%% *}
    kill $pid
  else
    echo "no such process"
    rm -f /tmp/pause /tmp/stop
  fi
elif [[ $1 = "-p" || $1 = "--pause" ||$1 = "-s" || $1 = "--step" || $1 = "-n" || $1 = "--now" ]]; then
  touch /tmp/pause /tmp/stop
  echo "Installer will halt after installation, and after the current step."
  print_usage
elif [[ -z $1 ]]; then
  touch /tmp/stop
  echo "Installer will halt after installation."
  print_usage
elif [[ $1 = "--unpause" ]]; then
  rm -f /tmp/pause
elif [[ $1 = "--unstop" ]]; then
  rm -f /tmp/pause /tmp/stop
else
  echo "[ERROR] Unknown token: $1"
fi
