#!/bin/sh

die () {
  msg="$1"
  code="$2"
  # exit code defaults to 1
  if printf "%s" "$code" | grep -q '^[0-9]+$'; then
    code=1
  fi
  # output message to stdout or stderr based on code
  if [ -n "$msg" ]; then
    if [ "$code" -eq 0 ]; then
      printf "%s\\n" "$msg"
    else
      printf "%s\\n" "$msg" >&2
    fi
  fi
  exit "$code"
}

yesno () {
  old_stty_cfg=$(stty -g)
  stty raw -echo
  yn=$(while ! head -c 1 | grep -i '[ny]'; do true; done)
  stty "$old_stty_cfg"
  case $yn in
    y ) result=0 ;;
    * ) result=1 ;;
  esac
  return $result
}

printf "This script will attempt to fetch and store your fediverse account webfinger\n"
printf "information. Cosmic is set up to serve that to users who search or mention you\n"
printf "at your cosmic.voyage username. If they send a message to %s@cosmic.voyage\n" "${USER}"
printf "it will properly deliver to your real account.\n\n"
printf "This script only needs to be run once to set up your redirect.\n\n"
printf "What is your fedi address? (format @username@server.com) [Enter to cancel]: \n"
read -r fedi
if [ -z "$fedi" ]; then
  die "" 2
else
  fediuser=$(printf "%s" "$fedi" | awk '{split($0,a,"@"); print a[2]}')
  fediserver=$(printf "%s" "$fedi" | awk '{split($0,a,"@"); print a[3]}')
  if [ -z "$fediuser" ]; then
    die "Improper address" 2
  fi
  if [ -z "$fediserver" ]; then
    die "Improper address" 2
  fi
  echo "$fediserver" "$fediuser"
  fediwebfinger="$(curl -s "https://${fediserver}/.well-known/webfinger?resource=acct:${fediuser}@${fediserver}")"
  printf "Found the following:\n\n%s\n" "$fediwebfinger"
  printf "\nDo you want to save it?\n"
  if yesno; then
    printf "%s" "$fediwebfinger" > "$HOME/.webfinger.json"
    printf "SAVED!\n"
  else
    printf "ABORT!\n"
  fi
fi
