#!/bin/sh
# Otar launcher.
#   otar              start the app
#   otar pair <code>  sign in the running app with a pairing code
#                   (for servers without a desktop); when the app is
#                   already signed in, this adds the code's account
#                   and keeps the existing one signed in too; when the
#                   account has two-step verification the command asks
#                   for the authenticator code (or a recovery code)
# The old command name `otterbeam` still works as an alias (a symlink made by the
# package's postinst).  # old-name: allow

if [ "$1" != "pair" ]; then
  exec /opt/otar/otar "$@"
fi

shift
if [ "$#" -ne 1 ]; then
  echo "Usage: otar pair <code>" >&2
  echo "Get a code on a device that is already signed in: Profile > Devices > Show pairing code." >&2
  exit 2
fi

code=$(printf '%s' "$1" | tr -cd '0-9')
case ${#code} in
  6|9) ;;
  *)
    echo "That doesn't look like a pairing code (6 digits)." >&2
    exit 2
    ;;
esac

run_dir="${OTAR_RUN_DIR:-${OTTERBEAM_RUN_DIR:-$HOME/.otterbeam/run}}"  # old-name: allow

if ! pgrep -u "$(id -u)" -x 'otar|otterbeam' >/dev/null 2>&1; then  # old-name: allow (an un-restarted old process keeps its old name)
  echo "Otar isn't running for this user." >&2
  echo "On a server without a desktop, start it as a background service first: see /usr/share/doc/otar/README.md" >&2
  exit 3
fi

umask 077
mkdir -p "$run_dir" || exit 1
id=$(od -An -N8 -tx1 /dev/urandom | tr -d ' \n')
tmp_request="$run_dir/pair-request.tmp.$$"
tmp_mfa="$run_dir/pair-mfa.tmp.$$"
trap 'rm -f "$tmp_request" "$tmp_mfa" "$run_dir/pair-request" "$run_dir/pair-mfa"' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM HUP

# Wait up to 30 seconds for the app's answer to this request id and print it in
# $status; returns 1 when no answer came.
wait_for_result() {
  tries=0
  while [ "$tries" -lt 60 ]; do
    if [ -f "$run_dir/pair-result" ] && grep -q "\"id\":\"$id\"" "$run_dir/pair-result" 2>/dev/null; then
      status=$(sed -n 's/.*"status":"\([a-z_]*\)".*/\1/p' "$run_dir/pair-result")
      rm -f "$run_dir/pair-result"
      return 0
    fi
    sleep 0.5
    tries=$((tries + 1))
  done
  return 1
}

no_answer() {
  echo "No answer from Otar within 30 seconds. Check it's running (systemctl --user status otterbeam-host) and try again." >&2
  exit 1
}

signed_in() {
  echo "If this computer was already signed in to another account, that account stays signed in too."
  echo "Last step: your other devices will show \"New device signed in\" -- tap Allow there."
  exit 0
}

rm -f "$run_dir/pair-result"
printf '{"id":"%s","code":"%s"}\n' "$id" "$code" > "$tmp_request" || exit 1
mv -f "$tmp_request" "$run_dir/pair-request" || exit 1
echo "Signing in..."

wait_for_result || no_answer

if [ "$status" = "mfa_required" ]; then
  echo "Two-step verification is on for this account."
  attempts=0
  while :; do
    if ! (: < /dev/tty) 2>/dev/null; then
      echo "This needs a terminal to type the code in. Run the command again in an interactive shell." >&2
      exit 1
    fi
    printf 'Enter the 6-digit code from your authenticator app (or a recovery code): ' > /dev/tty
    answer=
    read -r answer < /dev/tty || answer=
    # Keep only characters a code can contain, so the JSON below stays valid.
    answer=$(printf '%s' "$answer" | tr -cd '0-9A-Za-z -')
    if [ -z "$answer" ]; then
      attempts=$((attempts + 1))
      if [ "$attempts" -lt 5 ]; then
        echo "That code didn't work. Check the time on this computer and on your phone." >&2
        continue
      fi
      status=mfa_expired
      break
    fi
    rm -f "$run_dir/pair-result"
    printf '{"id":"%s","code":"%s"}\n' "$id" "$answer" > "$tmp_mfa" || exit 1
    mv -f "$tmp_mfa" "$run_dir/pair-mfa" || exit 1
    wait_for_result || no_answer
    attempts=$((attempts + 1))
    if [ "$status" = "mfa_invalid" ] && [ "$attempts" -lt 5 ]; then
      echo "That code didn't work. Check the time on this computer and on your phone." >&2
      continue
    fi
    break
  done
fi

case $status in
  ok)
    echo "Signed in."
    signed_in
    ;;
  ok_recovered)
    echo "Signed in with a recovery code. Two-step verification is now off for this account. Turn it on again in Otar: Account > Two-step verification."
    signed_in
    ;;
  already_signed_in)
    echo "This computer is already signed in to that account. Nothing to do."
    exit 0
    ;;
  invalid)
    echo "That code isn't valid. Get a new one: Profile > Devices > Show pairing code." >&2
    exit 1
    ;;
  expired)
    echo "That code has expired (codes last 10 minutes). Get a new one and try again." >&2
    exit 1
    ;;
  mfa_invalid|mfa_expired)
    if [ "${attempts:-0}" -ge 5 ]; then
      echo "Too many wrong codes. Get a new pairing code and run the command again." >&2
    else
      echo "The sign-in timed out. Get a new pairing code and run the command again." >&2
    fi
    exit 1
    ;;
  rate_limited)
    echo "Too many attempts. Wait a few minutes and try again." >&2
    exit 1
    ;;
  *)
    echo "Couldn't reach the Otar server. Check this computer's internet connection and try again." >&2
    exit 1
    ;;
esac
