#!/bin/bash
# Phase 7 legacy retirement — do NOT run until mac-sync is verified stable.
#
# Stops:
#   plum    — com.lilith.messaging + com.lilith.iphotos LaunchAgents
#   black   — messenger-imessage systemd service
#   apricot — media-gallery systemd service (after photo migration verified)
#
# Plists are left in place on plum for emergency rollback.
# DB + blobs on black/apricot are kept for archival reads.
#
# Pre-flight checklist (verify before running):
#   [ ] mac-sync client on plum: pgrep -x MacSyncApp returns a PID
#   [ ] mac-sync server on black: curl http://10.0.0.11:3201/health returns 200
#   [ ] iMessage flowing: new messages appear in mac-sync server within 30s
#   [ ] Photo migration complete: manage-apps status media-gallery apricot shows count matches
#   [ ] Email flowing: new Mail.app messages appear via mac-sync within sync cycle

set -euo pipefail

DRY_RUN=false
for arg in "$@"; do
  [[ "$arg" == "--dry-run" ]] && DRY_RUN=true
done

PLUM_HOST="${PLUM_HOST:-plum}"
BLACK_HOST="${BLACK_HOST:-10.0.0.11}"
APRICOT_HOST="${APRICOT_HOST:-10.0.0.13}"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

print_step()    { echo -e "${GREEN}▸${NC} $1"; }
print_warning() { echo -e "${YELLOW}⚠${NC} $1"; }
print_success() { echo -e "${GREEN}✓${NC} $1"; }

# Wrapper: in dry-run mode, print the command instead of executing it.
run() {
  if [[ "$DRY_RUN" == "true" ]]; then
    echo "[DRY-RUN] $*"
  else
    "$@"
  fi
}

echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}  Phase 7 — Legacy Service Retirement${NC}"
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e "${RED}This is DESTRUCTIVE. Only run after verifying mac-sync end-to-end.${NC}"
echo ""

if [[ "$DRY_RUN" == "true" ]]; then
    print_warning "DRY-RUN mode — no changes will be made"
elif [[ -t 0 ]]; then
    read -rp "Type 'retire' to confirm: " confirm
    if [[ "$confirm" != "retire" ]]; then
        echo "Aborted."
        exit 0
    fi
fi

# ── plum: unload legacy LaunchAgents ──────────────────────────────────────────
print_step "Unloading legacy LaunchAgents on $PLUM_HOST..."
run ssh "$PLUM_HOST" bash <<'PLUM'
for plist in \
    "$HOME/Library/LaunchAgents/com.lilith.messaging.plist" \
    "$HOME/Library/LaunchAgents/com.lilith.iphotos.plist"; do
    if [[ -f "$plist" ]]; then
        launchctl unload "$plist" 2>/dev/null || true
        echo "Unloaded: $plist (plist preserved for rollback)"
    fi
done
pkill -x LilithMessaging 2>/dev/null || true
pkill -x iPhotosSync 2>/dev/null || true
PLUM
print_success "plum: legacy agents unloaded"

# ── black: stop messenger-imessage ────────────────────────────────────────────
if [[ "${RETIRE_MESSENGER_IMESSAGE:-false}" != "true" ]]; then
    print_warning "Skipping messenger-imessage retirement (set RETIRE_MESSENGER_IMESSAGE=true to include)"
else
    print_step "Stopping messenger-imessage on $BLACK_HOST..."
    run ssh "$BLACK_HOST" "sudo systemctl stop messenger-imessage && sudo systemctl disable messenger-imessage"
    print_success "black: messenger-imessage stopped (DB preserved)"
fi

# ── black: disable iCloud IMAP sync ───────────────────────────────────────────
print_step "Checking iCloud IMAP sync env on $BLACK_HOST..."
print_warning "Set ICLOUD_SYNC_ENABLED=false in messenger-imessage env if you intend to re-enable it"

# ── apricot: stop media-gallery (after photo migration verified) ───────────────
if [[ "${RETIRE_MEDIA_GALLERY:-false}" == "true" ]]; then
    print_step "Stopping media-gallery on $APRICOT_HOST..."
    run ssh "$APRICOT_HOST" "sudo systemctl stop media-gallery && sudo systemctl disable media-gallery"
    print_success "apricot: media-gallery stopped (MinIO + DB preserved)"
else
    print_warning "Skipping media-gallery retirement (set RETIRE_MEDIA_GALLERY=true to include)"
fi

echo ""
print_success "Legacy retirement complete"
echo ""
echo "Rollback (if needed):"
echo "  plum:    ssh $PLUM_HOST 'launchctl load ~/Library/LaunchAgents/com.lilith.messaging.plist'"
echo "  black:   ssh $BLACK_HOST 'sudo systemctl start messenger-imessage'"
echo "  apricot: ssh $APRICOT_HOST 'sudo systemctl start media-gallery'"
