#!/usr/bin/env bash
# KYLA: prepare Thunderbird for linux-lt.org (Linux).
#
#   curl -fsSL https://thunderbird.linux-lt.org | bash
#
# Puts the KYLA add-ons for linux-lt.org into your Thunderbird profile (creating
# the profile if Thunderbird has never run): KYLA Connect (sign-in to mail,
# calendar and contacts at id.linux-lt.org), KYLA Jitsi (meetings on
# meet.linux-lt.org) and KYLA Seafile FileLink (large attachments on
# files.linux-lt.org). Then it starts
# Thunderbird, whose account setup opens by itself. Nothing is installed
# system-wide and nothing needs root.
set -euo pipefail
DOMAIN="linux-lt.org"
BASE="https://autoconfig.$DOMAIN/thunderbird"
# add-on ID, file on autoconfig.<domain>, name shown to the user
ADDONS=(
  "kyla-connect@$DOMAIN kyla-connect.xpi KYLA Connect"
  "kyla-jitsi@$DOMAIN kyla-jitsi.xpi KYLA Jitsi"
  "kyla-filelink@$DOMAIN kyla-filelink.xpi KYLA Seafile FileLink"
)
# Earlier builds: the combined KYLA add-on would register mail.$DOMAIN a
# second time next to KYLA Connect.
LEGACY=("kyla-tb@$DOMAIN")

# --------------------------------------------------------------------------
# Output: a braille snake while a step runs, then ✓ or ✗ in its place. Plain
# lines when the output is not a terminal (logs, CI).
# --------------------------------------------------------------------------
if [ -t 1 ]; then TTY=1; else TTY=""; fi
# A 4-dot snake running clockwise round the border of two braille cells.
FRAMES=(⡇⠀ ⠏⠀ ⠋⠁ ⠉⠉ ⠈⠙ ⠀⠹ ⠀⢸ ⠀⣰ ⢀⣠ ⣀⣀ ⣄⡀ ⣆⠀)
if [ -n "$TTY" ]; then
  C_OK=$'\e[32m' C_ERR=$'\e[31m' C_DIM=$'\e[2m' C_ACC=$'\e[36m' C_OFF=$'\e[0m'
  printf '\e[?25l'                                   # hide the cursor
  trap 'printf "\e[?25h"' EXIT                       # and always bring it back
  trap 'printf "\r\e[K\e[?25h"; exit 130' INT TERM
else
  C_OK="" C_ERR="" C_DIM="" C_ACC="" C_OFF=""
fi

say() { printf '%s\n' "$*"; }
ok()  { printf '  %s✓%s  %s\n' "$C_OK" "$C_OFF" "$*"; }
die() { printf '  %s✗%s  %s\n' "$C_ERR" "$C_OFF" "$*" >&2; exit 1; }

# step "message" command [args...]: run it with the snake beside the message.
step() {
  local msg=$1 pid rc i=0; shift
  if [ -z "$TTY" ]; then
    say "  ...  $msg"; "$@"; return
  fi
  "$@" >/dev/null 2>&1 &
  pid=$!
  while kill -0 "$pid" 2>/dev/null; do
    printf '\r  %s%s%s  %s' "$C_ACC" "${FRAMES[i++ % ${#FRAMES[@]}]}" "$C_OFF" "$msg"
    sleep 0.08
  done
  wait "$pid" && rc=0 || rc=$?
  printf '\r\e[K'
  if [ "$rc" -eq 0 ]; then ok "$msg"; else printf '  %s✗%s  %s\n' "$C_ERR" "$C_OFF" "$msg"; fi
  return "$rc"
}

say ""
say "  ${C_ACC}KYLA${C_OFF} · Thunderbird for $DOMAIN"
say "  ${C_DIM}mail, calendar and contacts with your organisation account${C_OFF}"
say ""

# --------------------------------------------------------------------------
# 1. Thunderbird must be installed (as a system package) and closed.
# --------------------------------------------------------------------------
if ! command -v thunderbird >/dev/null 2>&1; then
  die "Thunderbird is not installed. Install it (Fedora: sudo dnf install thunderbird; Debian: sudo apt install thunderbird) and run this again."
fi
if pgrep -u "$(id -u)" -x thunderbird >/dev/null 2>&1 || pgrep -u "$(id -u)" -f 'thunderbird-bin|/thunderbird/thunderbird' >/dev/null 2>&1; then
  die "Thunderbird is running. Close it and run this again."
fi
ok "Thunderbird $(thunderbird --version 2>/dev/null | awk '{print $NF}') found"

# Run Thunderbird once without a window, until <condition> holds (or 90 s),
# then let it shut down cleanly (SIGTERM) so it writes its state. Succeeds
# when the condition holds at the end.
background_run() { # condition-command [thunderbird args...]
  local cond=$1 pid; shift
  thunderbird --headless --no-remote "$@" >/dev/null 2>&1 &
  pid=$!
  for _ in $(seq 90); do eval "$cond" && break; sleep 1; done
  sleep 2
  kill -TERM "$pid" 2>/dev/null || true
  for _ in $(seq 30); do kill -0 "$pid" 2>/dev/null || break; sleep 1; done
  kill -KILL "$pid" 2>/dev/null || true
  wait "$pid" 2>/dev/null || true
  eval "$cond"
}

# --------------------------------------------------------------------------
# 2. The profile folder. Thunderbird 140+ uses ~/.config/thunderbird; older
# installs use ~/.thunderbird.
# --------------------------------------------------------------------------
find_root() {
  for r in "${XDG_CONFIG_HOME:-$HOME/.config}/thunderbird" "$HOME/.thunderbird"; do
    if [ -f "$r/installs.ini" ] || [ -f "$r/profiles.ini" ]; then echo "$r"; return; fi
  done
}
root=$(find_root)
if [ -z "$root" ]; then
  # Never started: let Thunderbird create its own default profile, so it is
  # the one it uses from now on.
  step "Creating your Thunderbird profile" \
    background_run '[ -n "$(find_root)" ] && [ -f "$(find_root)/installs.ini" ]' \
    || die "Thunderbird did not create a profile."
  root=$(find_root)
fi

# The profile this Thunderbird starts with: the install's default
# (installs.ini), else the one marked Default=1 in profiles.ini.
rel=$(sed -n 's/^Default=//p' "$root/installs.ini" 2>/dev/null | head -1)
if [ -z "$rel" ]; then
  rel=$(awk -F= '/^\[Profile/{p=""} /^Path=/{p=$2} /^Default=1/{if(p!=""){print p; exit}}' "$root/profiles.ini")
fi
[ -n "$rel" ] || die "Could not find your Thunderbird profile in $root."
case $rel in /*) profile=$rel ;; *) profile="$root/$rel" ;; esac
[ -d "$profile" ] || die "Profile folder $profile is missing."
ok "Profile ${C_DIM}${profile/#$HOME/\~}${C_OFF}"

# --------------------------------------------------------------------------
# 3. The add-ons, each under its ID.
# --------------------------------------------------------------------------
mkdir -p "$profile/extensions"
for id in "${LEGACY[@]}"; do
  if [ -e "$profile/extensions/$id.xpi" ]; then rm -f "$profile/extensions/$id.xpi"; ok "Removed the old $id"; fi
done
fetch() { curl -fsSL "$1" -o "$2.part" && mv "$2.part" "$2"; }   # url dest
ids=()
for a in "${ADDONS[@]}"; do
  read -r id file name <<<"$a"
  step "Downloading $name" fetch "$BASE/$file" "$profile/extensions/$id.xpi" \
    || die "Could not download $BASE/$file"
  ids+=("$id")
done

# Thunderbird registers an add-on that appears in an existing profile on its
# next start, but only starts it on the start after that. Do that first start
# here, without a window, so the user's start already has them (and with KYLA
# Connect the sign-in for mail.$DOMAIN).
registered() {
  local id
  for id in "${ids[@]}"; do grep -q "\"$id\"" "$profile/extensions.json" 2>/dev/null || return 1; done
}
step "Registering the add-ons with Thunderbird" background_run registered --profile "$profile" \
  || die "Thunderbird did not register the add-ons."

# --------------------------------------------------------------------------
# 4. Start Thunderbird: with no account yet, its account setup opens.
# --------------------------------------------------------------------------
say ""
if [ -z "${KYLA_NO_START:-}" ] && { [ -n "${DISPLAY:-}" ] || [ -n "${WAYLAND_DISPLAY:-}" ]; }; then
  setsid thunderbird >/dev/null 2>&1 < /dev/null &
  ok "Thunderbird started"
  say "     Enter your name and your @$DOMAIN address, then sign in at id.$DOMAIN."
else
  say "  Start Thunderbird, enter your name and your @$DOMAIN address,"
  say "  then sign in at id.$DOMAIN."
fi
say ""
