#!/usr/bin/env bash
# Clean up the legacy whp-suspended container if it exists.
#
# The suspension page is now served by the haproxy-manager container's built-in
# Flask /suspended route (same Flask app that serves /default-page and
# /blocked-ip), so the separate whp-suspended nginx container is no longer
# needed. Hosts that deployed the previous (separate-container) design will
# have this container left over; this script removes it and also recreates
# haproxy-manager so it picks up the new image (which adds the /suspended route)
# and the new HAPROXY_SUSPENSION_ENABLED env var.
#
# Idempotent: safe to re-run.

set -euo pipefail

if docker ps -a --filter name=whp-suspended --format='{{.Names}}' | grep -qx whp-suspended; then
    echo "Removing legacy whp-suspended container..."
    docker stop whp-suspended 2>/dev/null || true
    docker rm whp-suspended 2>/dev/null || true
    echo "  removed"
else
    echo "No legacy whp-suspended container; nothing to remove"
fi

# Recreate haproxy-manager so it pulls the new image (with /suspended route)
# and picks up the new HAPROXY_SUSPENSION_ENABLED env var.
#
# Critically: update.sh runs versioned scripts BEFORE rsyncing scripts/, so at
# this point /root/whp/scripts/container-manager.sh is still the OLD copy that
# sets the OLD HAPROXY_SUSPENSION_BACKEND env var. Install the new one from
# the tarball first (same pattern as setup-customer-watchdog.sh).
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARBALL_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
NEW_CM="$TARBALL_ROOT/scripts/container-manager.sh"
if [ -f "$NEW_CM" ]; then
    install -m 0755 "$NEW_CM" /root/whp/scripts/container-manager.sh
    echo "Installed updated container-manager.sh from tarball"
fi

if [ -x /root/whp/scripts/container-manager.sh ]; then
    echo "Recreating haproxy-manager to pick up new image + env var..."
    /root/whp/scripts/container-manager.sh recreate haproxy-manager
else
    echo "WARN: /root/whp/scripts/container-manager.sh not present; skip haproxy-manager recreate"
fi

echo "Legacy suspension cleanup complete."
