#!/usr/bin/env bash
# adom-rss-gchat installer — run on a fresh (or existing) Adom container:
#
#   curl -fsSL https://wiki.adom.inc/download/adom/adom-rss-gchat/1.1.0/install.sh | bash
#
# Idempotent: re-running upgrades the code and never touches your data
# (feeds, seen-item state, editor token, env config all live in ~/rss-gchat).
# No Rust, git, or wiki CLI needed — everything downloads over plain HTTPS.
set -euo pipefail

VERSION="1.1.0"
BASE="https://wiki.adom.inc/download/adom/adom-rss-gchat/$VERSION"
TARBALL="adom-rss-gchat-$VERSION-linux-x86_64.tar.gz"

APP_DIR="$HOME/adom-rss-gchat"
DATA_DIR="$HOME/rss-gchat"
BIN="/usr/local/bin/adom-rss-gchat"

echo "== adom-rss-gchat $VERSION installer =="

# 1) System deps: cron (scheduler) + python3 (editor). default-light lacks both.
NEED=""
command -v crontab >/dev/null 2>&1 || NEED="$NEED cron"
command -v python3 >/dev/null 2>&1 || NEED="$NEED python3"
if [ -n "$NEED" ]; then
  echo "-- installing$NEED"
  sudo apt-get -qq update >/dev/null
  sudo apt-get -qq install -y $NEED >/dev/null
fi
pgrep -x cron >/dev/null 2>&1 || sudo service cron start >/dev/null 2>&1 || sudo cron

# 2) Download + unpack the release bundle.
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
echo "-- downloading $TARBALL"
curl -fsSL "$BASE/$TARBALL" -o "$TMP/bundle.tar.gz"
tar -xzf "$TMP/bundle.tar.gz" -C "$TMP"

# 3) Stop any running instance (old or new binary name) before swapping code.
for pf in "$DATA_DIR/bridge.pid" "$DATA_DIR/editor.pid"; do
  [ -f "$pf" ] && kill "$(cat "$pf" 2>/dev/null)" 2>/dev/null || true
  rm -f "$pf"
done
for name in adom-rss-gchat rss-gchat-bridge; do
  for p in $(pidof "$name" 2>/dev/null); do kill "$p" 2>/dev/null || true; done
done

# 4) Install binary + app files. A pre-1.0 git checkout at APP_DIR is set aside.
if [ -d "$APP_DIR/.git" ]; then
  mv "$APP_DIR" "$APP_DIR.git-backup.$(date +%s)"
  echo "-- moved old git checkout aside"
fi
sudo install -m755 "$TMP/bin/adom-rss-gchat" "$BIN"
sudo rm -f /usr/local/bin/rss-gchat-bridge   # pre-1.0 binary name
mkdir -p "$APP_DIR/editor" "$APP_DIR/service"
install -m644 "$TMP/editor/index.html" "$APP_DIR/editor/index.html"
install -m644 "$TMP/editor/server.py"  "$APP_DIR/editor/server.py"
install -m755 "$TMP/service/watchdog.sh" "$APP_DIR/service/watchdog.sh"
echo "$VERSION" > "$APP_DIR/VERSION"

# 5) Data dir — created once, never overwritten on upgrade.
mkdir -p "$DATA_DIR"
umask 077
q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
if [ ! -f "$DATA_DIR/env" ]; then
  # Auth default: "Sign in with Adom" when the container can identify its
  # owner (the pinned editor URL then carries no secret); token mode otherwise.
  # Override by exporting EDITOR_AUTH=token|adom before running the installer.
  if [ -z "${EDITOR_AUTH:-}" ]; then
    [ -s /var/run/adom/api-key ] && EDITOR_AUTH=adom || EDITOR_AUTH=token
  fi
  {
    # GCHAT_WEBHOOK_URL is optional: normally each feed carries its own
    # webhook, entered in the web editor. Export it before running this
    # installer to set a deployment-wide default instead.
    [ -n "${GCHAT_WEBHOOK_URL:-}" ] && echo "GCHAT_WEBHOOK_URL=$(q "$GCHAT_WEBHOOK_URL")"
    echo "POLL_INTERVAL_MINUTES=$(q "${POLL_INTERVAL_MINUTES:-30}")"
    echo "SEED_ON_FIRST_RUN=true"
    echo "RUST_LOG=info"
    echo "RSS_EDITOR_PORT=$(q "${RSS_EDITOR_PORT:-8842}")"
    echo "EDITOR_AUTH=$(q "$EDITOR_AUTH")"
    [ -n "${EDITOR_ALLOWED_USERS:-}" ] && echo "EDITOR_ALLOWED_USERS=$(q "$EDITOR_ALLOWED_USERS")"
  } > "$DATA_DIR/env"
  chmod 600 "$DATA_DIR/env"
fi
[ -f "$DATA_DIR/feeds.json" ] || printf '{\n  "feeds": []\n}\n' > "$DATA_DIR/feeds.json"
if [ ! -s "$DATA_DIR/editor.token" ]; then
  python3 -c "import secrets;print(secrets.token_urlsafe(32))" > "$DATA_DIR/editor.token"
  chmod 600 "$DATA_DIR/editor.token"
fi

# 6) Watchdog cron (every 2 min). || true keeps set -e alive on a fresh crontab.
CRON="*/2 * * * * $APP_DIR/service/watchdog.sh >> $DATA_DIR/watchdog.log 2>&1"
EXISTING_CRON="$(crontab -l 2>/dev/null || true)"
FILTERED_CRON="$(echo "$EXISTING_CRON" | grep -v 'rss-gchat' || true)"
printf '%s\n%s\n' "$FILTERED_CRON" "$CRON" | sed '/^$/d' | crontab -

# 7) Launch + verify.
bash "$APP_DIR/service/watchdog.sh"
sleep 2
BOK=0; EOK=0
p="$(cat "$DATA_DIR/bridge.pid" 2>/dev/null)" && kill -0 "$p" 2>/dev/null && BOK=1
p="$(cat "$DATA_DIR/editor.pid" 2>/dev/null)" && kill -0 "$p" 2>/dev/null && EOK=1
if [ "$BOK" = 1 ] && [ "$EOK" = 1 ]; then
  echo "OK: bridge + editor running ($("$BIN" --version))."
else
  echo "FAILED to launch (bridge=$BOK editor=$EOK). Logs:" >&2
  tail -n 15 "$DATA_DIR/bridge.log" "$DATA_DIR/editor.log" 2>/dev/null >&2 || true
  exit 1
fi

PORT="$(. "$DATA_DIR/env" 2>/dev/null; echo "${RSS_EDITOR_PORT:-8842}")"
MODE="$(. "$DATA_DIR/env" 2>/dev/null; echo "${EDITOR_AUTH:-token}")"
cat <<STEPS

== Installed. Finish setup (2 steps) ==

1. Expose the feed editor. From your Adom dev container (where adom-cli
   is installed), map the editor port on THIS container:

     adom-cli carbon containers port-add <this-container-slug> --port $PORT --prefix rss-editor

   The command returns a hostname like rss-editor-xxxx.adom.cloud.
STEPS
if [ "$MODE" = "adom" ]; then
  cat <<STEPS

2. Open the editor and follow its on-page setup guide:

     https://<hostname-from-step-1>/

   You'll sign in with your Adom account (a one-time confirmation code per
   browser). Only this container's owner can get in; allow teammates by
   adding EDITOR_ALLOWED_USERS=name1,name2 to ~/rss-gchat/env.

The URL carries no secret — pin it to your Chat space as-is.
STEPS
else
  TOKEN="$(cat "$DATA_DIR/editor.token")"
  cat <<STEPS

2. Open the editor and follow its on-page setup guide:

     https://<hostname-from-step-1>/?token=$TOKEN

   The guide walks you through creating a Google Chat webhook and adding
   your first feed. When done, pin that URL to your Chat space so feed
   edits are one click away.

Treat the URL like a password: anyone with it can edit your feeds.
STEPS
fi
echo "To upgrade later, re-run this installer — data and feeds are preserved."
