#!/bin/sh
# Resend BFCM in your terminal, with the page's shortcuts.
#   curl -s https://resend.com/bfcm.sh | sh
# First pick the board: 1 global, 2 your team (confirm a code on
# resend.com). Then: M mode, S sound, R popup, 1-9, 0, - . and ,
# customer popups, X close popup, H F E G T open pages, Q quit.

BASE="${BFCM_URL:-https://resend.com}"
THEMES="classic green dracula amber turbo cga"
theme="${1:-classic}"
sound=off
popup=off
closed=0
logo=""
boot=on
pid=""
resized=""
# The team board pass, kept in memory only.
pass=""
notice=""
failures=0
retry_at=""

if ! [ -r /dev/tty ] || ! command -v curl >/dev/null 2>&1; then
  echo "bfcm.sh needs a terminal and curl" >&2
  exit 1
fi

# The stream's response headers, to tell an ended pass from a dropped
# connection.
if ! headers=$(mktemp 2>/dev/null); then
  echo "bfcm.sh needs mktemp" >&2
  exit 1
fi
saved=$(stty -g </dev/tty)

read_key() {
  dd bs=1 count=1 2>/dev/null </dev/tty
}

stop_stream() {
  if [ -n "$pid" ]; then
    kill "$pid" 2>/dev/null
    wait "$pid" 2>/dev/null
    pid=""
  fi
}

# The pass goes in on stdin, so it never shows in the process list.
start_stream() {
  stop_stream
  retry_at=""
  : >"$headers"
  size=$(stty size </dev/tty)
  url="$BASE/bfcm/live.txt?cols=${size#* }&rows=${size% *}&theme=$theme&sound=$sound&popup=$popup&closed=$closed&logo=$logo&boot=$boot&keys=on"
  if [ -n "$pass" ]; then
    printf 'Authorization: BfcmPass %s' "$pass" | curl -sN -D "$headers" -H @- "$url" >/dev/tty &
  else
    curl -sN "$url" >/dev/tty &
  fi
  pid=$!
  boot=off
}

next_theme() {
  first=""
  take=""
  for name in $THEMES; do
    [ -z "$first" ] && first=$name
    if [ -n "$take" ]; then
      theme=$name
      return
    fi
    [ "$name" = "$theme" ] && take=1
  done
  theme=$first
}

open_page() {
  if command -v open >/dev/null 2>&1; then
    open "$1" >/dev/null 2>&1
  elif command -v xdg-open >/dev/null 2>&1; then
    xdg-open "$1" >/dev/null 2>&1 &
  fi
}

json_field() {
  printf '%s' "$2" | sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p"
}

post_secret() {
  printf '%s' "$1" | curl -s -m 10 -X POST --data-urlencode "secret@-" "$BASE/bfcm/pass/$2"
}

end_pass() {
  if [ -n "$1" ]; then
    post_secret "$1" end >/dev/null 2>&1
  fi
}

screen_text() {
  printf '\033[0m\033[H\033[2J\n' >/dev/tty
  for line in "$@"; do
    printf '  %s\n' "$line" >/dev/tty
  done
}

show_menu() {
  screen_text "Resend Email Department BFCM'26" "" \
    "[1] Global" \
    "[2] Your team (confirm a code on resend.com)" \
    "[Q] Quit" "" "$notice"
}

# A device code flow. The browser sees only the code, so only this script
# can collect the pass.
link_team() {
  started=$(curl -s -m 10 -w '\n%{http_code}' -X POST "$BASE/bfcm/pass/start")
  secret=$(json_field secret "$started")
  code=$(json_field code "$started")
  link=$(json_field url "$started")
  confirm=$(json_field confirm_url "$started")
  if [ -z "$secret" ] || [ -z "$code" ] || [ -z "$link" ] || [ -z "$confirm" ]; then
    case "$(printf '%s' "$started" | tail -n 1)" in
      429) notice="Not linked: too many codes from your network. Wait a minute, then try again." ;;
      000) notice="Not linked: couldn't reach $BASE." ;;
      *) notice="Not linked: $BASE couldn't start a code. Try again in a minute." ;;
    esac
    return 1
  fi

  # The code in a box, bold and spaced out like the confirm page shows it.
  spaced=$(printf '%s' "$code" | sed 's/./& /g; s/ $//')
  rule=$(printf '%*s' $((${#spaced} + 12)) '' | sed 's/ /─/g')
  blank=$(printf '%*s' $((${#spaced} + 12)) '')
  bold=$(printf '\033[1m')
  plain=$(printf '\033[0m')
  screen_text "Your code:" "" \
    "┌${rule}┐" \
    "│${blank}│" \
    "│      ${bold}${spaced}${plain}      │" \
    "│${blank}│" \
    "└${rule}┘" "" \
    "Your browser opens resend.com. Check it shows this code, then confirm." \
    "If no browser opened, go to $link and enter the code." \
    "Never share the code or the link. Resend never asks you for them." "" \
    "Waiting for you to confirm...  [Q] Cancel"
  open_page "$confirm"

  ticks=0
  # A clock deadline, so a slow poll does not stretch the 10-minute wait.
  deadline=$(($(date +%s) + 600))
  while [ "$(date +%s)" -lt "$deadline" ]; do
    case "$(read_key)" in
      q | Q)
        end_pass "$secret"
        notice="Not linked."
        return 1
        ;;
    esac
    if [ $((ticks % 10)) -eq 0 ]; then
      case "$(post_secret "$secret" poll)" in
        *'"approved"'*)
          pass=$secret
          return 0
          ;;
        *'"expired"'*)
          notice="Not linked: the code expired."
          return 1
          ;;
      esac
    fi
    ticks=$((ticks + 1))
  done
  end_pass "$secret"
  notice="Not linked: the code expired."
  return 1
}

choose_board() {
  show_menu
  while :; do
    case "$(read_key)" in
      1)
        notice=""
        return
        ;;
      2)
        if link_team; then
          notice=""
          return
        fi
        show_menu
        ;;
      q | Q) exit 0 ;;
    esac
  done
}

restore_terminal() {
  stop_stream
  stty "$saved" </dev/tty
  printf '\033[0m\033[?25h\033[?1049l' >/dev/tty
  rm -f "$headers"
  end_pass "$pass"
}

trap restore_terminal EXIT
trap 'exit 0' INT TERM HUP
trap 'resized=1' WINCH

printf '\033[?1049h\033[?25l' >/dev/tty
stty -icanon -echo min 0 time 2 </dev/tty
choose_board
start_stream

while :; do
  key=$(read_key)
  if [ -n "$resized" ]; then
    resized=""
    start_stream
  fi
  case "$key" in
    m | M)
      next_theme
      start_stream
      ;;
    s | S)
      if [ "$sound" = on ]; then sound=off; else sound=on; fi
      start_stream
      ;;
    r | R)
      if [ "$popup" = on ]; then popup=off; else popup=on; fi
      start_stream
      ;;
    1) logo=raycast; start_stream ;;
    2) logo=paper; start_stream ;;
    3) logo=firecrawl; start_stream ;;
    4) logo=airgoods; start_stream ;;
    5) logo=dub; start_stream ;;
    6) logo=zernio; start_stream ;;
    7) logo=polar; start_stream ;;
    8) logo=mintlify; start_stream ;;
    9) logo=sketch; start_stream ;;
    0) logo=slash; start_stream ;;
    -) logo=gumroad; start_stream ;;
    .) logo=convex; start_stream ;;
    ,) logo=town; start_stream ;;
    x | X)
      logo=""
      popup=off
      closed=$(date +%s)
      start_stream
      ;;
    h | H) open_page "$BASE/home" ;;
    f | F) open_page "$BASE/features/forge" ;;
    e | E) open_page "$BASE/enterprise" ;;
    g | G) open_page "$BASE/signup" ;;
    t | T) open_page "https://resend.studio" ;;
    q | Q) exit 0 ;;
  esac
  if [ -n "$retry_at" ]; then
    if [ "$(date +%s)" -ge "$retry_at" ]; then
      start_stream
    fi
  elif ! kill -0 "$pid" 2>/dev/null; then
    # A proxy can write its own status line first, so the last one counts.
    status=$(grep '^HTTP/' "$headers" | tail -n 1)
    case "$status" in
      *' 401'*)
        # A 401 means the pass no longer works, so go back to the menu.
        end_pass "$pass"
        pass=""
        failures=0
        notice="Your team link ended. Pick a board again."
        choose_board
        start_stream
        ;;
      '' | *' 200'*)
        failures=0
        sleep 1
        start_stream
        ;;
      *)
        # Each try reads the team's stats again, so a failing board backs off.
        failures=$((failures + 1))
        delay=$((failures * failures * 2))
        [ "$delay" -gt 30 ] && delay=30
        printf '\033[0m\n  The board is not answering. Trying again in %ss.\033[K\n' "$delay" >/dev/tty
        retry_at=$(($(date +%s) + delay))
        ;;
    esac
  fi
done
