#/bin/sh

set -eu

# As this is normally run under a tmux session, the error messages disappear
# after exit, and as those might be informative we help user to see them:
exit_error_after_enter() {
  printf '%s\n' "$1" >&2
  read -p '  (Press Enter to continue) ' answer
  exit 1
}

if ! mountpoint -q /state; then
  exit_error_after_enter 'puavo-reset can not be run unless /state is mounted'
fi

reset_override_path='/state/etc/puavo/reset_override'

if ! reset_state=$(jq -r .reset /etc/puavo/device.json) \
  || [ -z "$reset_state" -o "$reset_state" = 'null' ]; then
    # no reset state
    rm -f "$reset_override_path"
    exit_error_after_enter \
      'No reset request even though puavo-reset is run'
fi

get_key() { printf "%s\n" "$reset_state" | jq -r --arg key "$1" '.[$key]'; }

from=$(        get_key from)
mode=$(        get_key mode)
operation=$(   get_key operation)
pin=$(         get_key pin)
request_time=$(get_key request-time)

request_time_for_tz=$(date --date="$request_time")

has_windows() {
  [ -e /images/boot/.puavo_windows_partition ]
}

show_info() {
  local requires_network reset_operation_msg
  reset_operation_msg=$1
  requires_network=$2

  cat <<EOF
  >>> PUAVO RESET MODE <<<
  >>> ================ <<<

This host has been marked for reset in Puavo.
User home directories will be wiped out
and system will be returned to factory defaults.

${reset_operation_msg}
EOF

  if $requires_network; then
    echo 'Resetting the Windows operating system requires network access.'
  fi

  cat <<EOF

Detailed request information:
  operation:            ${operation}
  request came from:    ${from}
  request time:         ${request_time_for_tz}

EOF
}

connect_to_network() {
  local answer force
  force=$1
  if ! $force; then
    if [ "$(LANG=C nmcli networking connectivity)" = 'full' ]; then
      echo 'You are connected to a network.'
      echo
      return 0
    else
      read -p 'You are NOT connected to a network, press ENTER to connect: ' \
              answer
    fi
  fi

  nmcli radio wifi on || true
  nmtui || true

  [ "$(LANG=C nmcli networking connectivity)" = 'full' ]
}

ask_pin_to_proceed() {
  local pin pin_answer reset_operation_msg requires_network
  pin=$1
  reset_operation_msg=$2
  requires_network=$3

  while true; do
    clear
    show_info "$reset_operation_msg" "$requires_network"
    if $requires_network; then
      while ! connect_to_network false; do sleep 1; done
    fi

    echo 'You must provide the correct PIN code to proceed with the operation.'
    if $requires_network; then
      echo 'You may also provide a special PIN "nmtui" to switch networks.'
    fi

    read -p '  PIN CODE: ' pin_answer
    if [ "$pin_answer" = 'nmtui' -o "$pin_answer" = 'TUITUI' ]; then
      connect_to_network true || true
      continue
    elif [ "$pin_answer" = "$pin" ]; then
      echo '    PIN OK, continuing...'
      return 0
    fi
    echo '    WRONG PIN!'
    sleep 1
  done
}

requires_network=false

reset_operation_msg=''
case "$operation" in
  reset)
    if has_windows; then
      requires_network=true
      prltfd_args='--force --os-targets=PuavoOS,Windows'
      reset_operation_msg='Resetting both Puavo OS and Windows.'
    else
      prltfd_args='--force --os-targets=PuavoOS'
      reset_operation_msg='Resetting Puavo OS only (Windows is not installed).'
    fi
    ;;
  reset-puavo-os)
    prltfd_args='--force --os-targets=PuavoOS'
    if has_windows; then
      reset_operation_msg='Resetting Puavo OS only (leaving Windows as is).'
    else
      reset_operation_msg='Resetting Puavo OS only (Windows is not installed).'
    fi
    ;;
  reset-windows)
    if ! has_windows; then
      exit_error_after_enter \
        'Requested Windows reset only but Windows is not installed'
    fi
    requires_network=true
    reset_operation_msg='Resetting Windows only.'
    prltfd_args='--force --os-targets=Windows'
    ;;
  *)
    exit_error_after_enter "Unknown operation: '${operation}'"
    ;;
esac

case "$mode" in
  ask_pin)
    ask_pin_to_proceed "$pin" "$reset_operation_msg" "$requires_network"
    sleep 2
    ;;
  *)
    exit_error_after_enter "Unsupported mode '${mode}'"
    ;;
esac

if ! puavo-reset-laptop-to-factory-defaults $prltfd_args; then
  exit_error_after_enter 'Device reset failed'
fi

# puavo-reset-laptop-to-factory-defaults will not reboot after a Windows-only
# reset, but we must
reboot
