#!/bin/bash
# rebuild-symlinks.sh — recreate every server-side symlink the live site needs.
#
# Run automatically by github-webhook.js after every successful git pull, and
# can also be run manually via:
#
#     ssh root@198.211.114.12 'bash /var/www/adampowell.pro/scripts/rebuild-symlinks.sh'
#
# Idempotent: ln -sfn replaces any existing symlink/file/empty-dir at the
# target. Refuses to clobber a non-empty directory by design — that would
# usually mean a Tier 2 cleanup left a real dir on disk that the symlink
# would shadow, and that needs human attention.
#
# After the 2026-04-10 Tier 3 restructure, all app sources live under
# /var/www/adampowell.pro/apps/.

set -u
REPO=/var/www/adampowell.pro
HTML=$REPO/html
APPS=$REPO/apps

ok=0
warn=0
err=0

# resolve <name> — pick the first existing source path. After the 2026-04-10
# restructure the canonical home is apps/<name>; the legacy top-level path is
# kept as a fallback so this script works during the transition window between
# the webhook landing and the restructure landing.
resolve() {
    local name="$1"
    if [ -e "$APPS/$name" ]; then
        echo "$APPS/$name"
    elif [ -e "$REPO/$name" ]; then
        echo "$REPO/$name"
    else
        echo ""
    fi
}

link() {
    local link_path="$1"
    local target="$2"

    if [ -z "$target" ] || [ ! -e "$target" ]; then
        echo "  ERR  $link_path -> $target  (target missing)"
        err=$((err+1))
        return
    fi

    # If link_path exists and is NOT a symlink, refuse unless it's empty
    if [ -e "$link_path" ] && [ ! -L "$link_path" ]; then
        if [ -d "$link_path" ] && [ -z "$(ls -A "$link_path" 2>/dev/null)" ]; then
            rmdir "$link_path"
        else
            echo "  WARN $link_path  (exists as non-empty file/dir, leaving alone)"
            warn=$((warn+1))
            return
        fi
    fi

    ln -sfn "$target" "$link_path"
    echo "  ok   $link_path -> $target"
    ok=$((ok+1))
}

# Compatibility shims at the repo root so nginx 'root /var/www/adampowell.pro;'
# blocks (NDA, purchase-orders) keep working without an nginx edit. Only useful
# AFTER the restructure (when apps/nda exists). Skipped quietly otherwise.
if [ -d "$APPS/nda" ]; then
    link "$REPO/nda" "$APPS/nda"
fi
if [ -d "$APPS/purchase-orders" ]; then
    link "$REPO/purchase-orders" "$APPS/purchase-orders"
fi

# Web-root symlinks. Each tries apps/<name> first, then falls back to the
# legacy top-level path so this works on both pre- and post-restructure trees.
link "$HTML/infus"               "$(resolve infus)"
link "$HTML/POCUS"               "$(resolve POCUS)"
pocus_root="$(resolve POCUS)"
[ -n "$pocus_root" ] && link "$HTML/cardiac-anes.html" "$pocus_root/cardiac-anes.html"
link "$HTML/mac"                 "$(resolve mac)"
link "$HTML/bp"                  "$(resolve bp)"
link "$HTML/mickey"              "$(resolve mickey)"
link "$HTML/photo"               "$(resolve photography)"
link "$HTML/crna-pay-calculator" "$(resolve crna-pay-calculator)"
link "$HTML/case-tracker"        "$(resolve case-tracker)"
pulse_root="$(resolve pulse)"
[ -n "$pulse_root" ] && link "$HTML/pulse" "$pulse_root/client/dist"
atlas_root="$(resolve Atlas)"
[ -n "$atlas_root" ] && link "$HTML/atlas" "$atlas_root/pwa/public"

# Investing index.html is symlinked from inside an existing dir so server-only
# files (secrets.js) can sit alongside it.
mkdir -p "$HTML/investing"
inv_root="$(resolve investment-calculators)"
[ -n "$inv_root" ] && link "$HTML/investing/index.html" "$inv_root/index.html"

# ANSReset PWA (Nervous System Reset). Same pattern as investing — html/ANSReset
# is a real dir so secrets.js can sit alongside the symlinked PWA assets.
mkdir -p "$HTML/ANSReset"
ans_root="$(resolve ANSReset)"
if [ -n "$ans_root" ]; then
    link "$HTML/ANSReset/index.html"    "$ans_root/index.html"
    link "$HTML/ANSReset/sw.js"         "$ans_root/sw.js"
    link "$HTML/ANSReset/manifest.json" "$ans_root/manifest.json"
    link "$HTML/ANSReset/icon-192.png"  "$ans_root/icon-192.png"
    link "$HTML/ANSReset/icon-512.png"  "$ans_root/icon-512.png"
fi

# Remote PWA (FormFill command relay). Per-file symlinks like the other
# sync-backend apps. Proxy at /remote/api/ → 127.0.0.1:3010 (remote.service).
mkdir -p "$HTML/remote"
remote_root="$(resolve remote)"
if [ -n "$remote_root" ]; then
    link "$HTML/remote/index.html"    "$remote_root/index.html"
    link "$HTML/remote/sw.js"         "$remote_root/sw.js"
    link "$HTML/remote/manifest.json" "$remote_root/manifest.json"
    link "$HTML/remote/icon-192.png"  "$remote_root/icon-192.png"
    link "$HTML/remote/icon-512.png"  "$remote_root/icon-512.png"
fi

# RandEmail PWA (SimpleLogin alias manager). Per-file symlinks so the html
# dir is a real dir; proxy at /RandEmail/api/ → 127.0.0.1:3009 (randemail.service).
mkdir -p "$HTML/RandEmail"
re_root="$(resolve RandEmail)"
if [ -n "$re_root" ]; then
    link "$HTML/RandEmail/index.html"    "$re_root/index.html"
    link "$HTML/RandEmail/sw.js"         "$re_root/sw.js"
    link "$HTML/RandEmail/manifest.json" "$re_root/manifest.json"
    link "$HTML/RandEmail/icon-192.png"  "$re_root/icon-192.png"
    link "$HTML/RandEmail/icon-512.png"  "$re_root/icon-512.png"
fi

# Todos PWA (ADAMANT Todo Lists). No secrets.js needed (no external API),
# but uses the same per-file symlink pattern for consistency.
mkdir -p "$HTML/todos"
todos_root="$(resolve todos)"
if [ -n "$todos_root" ]; then
    link "$HTML/todos/index.html"    "$todos_root/index.html"
    link "$HTML/todos/sw.js"         "$todos_root/sw.js"
    link "$HTML/todos/manifest.json" "$todos_root/manifest.json"
    link "$HTML/todos/icon-192.png"  "$todos_root/icon-192.png"
    link "$HTML/todos/icon-512.png"  "$todos_root/icon-512.png"
fi

# Case-tracker needs an internal index.html alias since the real file is named
# case-tracker.html.
ct_root="$(resolve case-tracker)"
if [ -n "$ct_root" ] && [ ! -e "$ct_root/index.html" ]; then
    ln -s case-tracker.html "$ct_root/index.html"
    echo "  ok   $ct_root/index.html -> case-tracker.html"
    ok=$((ok+1))
fi

# Pet Feed PWA (Mickey & Nala meal tracker).
mkdir -p "$HTML/petfeed"
petfeed_root="$(resolve petfeed)"
if [ -n "$petfeed_root" ]; then
    link "$HTML/petfeed/index.html"    "$petfeed_root/index.html"
    link "$HTML/petfeed/sw.js"         "$petfeed_root/sw.js"
    link "$HTML/petfeed/manifest.json" "$petfeed_root/manifest.json"
    link "$HTML/petfeed/icon-192.png"  "$petfeed_root/icon-192.png"
    link "$HTML/petfeed/icon-512.png"  "$petfeed_root/icon-512.png"
fi

# Shared Todo landing page + raw Scriptable script for copy-paste into the Scriptable iOS app. API at /sharedtodo/api/ proxied to 127.0.0.1:3014 (sharedtodo.service).
mkdir -p "$HTML/sharedtodo"
sharedtodo_root="$(resolve sharedtodo)"
if [ -n "$sharedtodo_root" ]; then
    link "$HTML/sharedtodo/index.html"    "$sharedtodo_root/index.html"
    link "$HTML/sharedtodo/style.css"     "$sharedtodo_root/style.css"
    link "$HTML/sharedtodo/SharedTodo.js" "$sharedtodo_root/SharedTodo.js"
fi

echo
echo "rebuild-symlinks: $ok ok, $warn warn, $err err"

# Restart the remote systemd service so apps/server/remote/server.js changes
# go live. The github webhook only restarts pm2's janda-app; remote runs as
# its own systemd unit on port 3010 and needs an explicit kick. Idempotent,
# cheap (~0.5s), and tolerant of failure (|| true) so it never blocks deploy.
systemctl restart remote.service 2>/dev/null || true
echo "remote.service: restart requested"

exit 0
