#!/bin/bash
# /opt/dashcaddy/lock-caddyfile.sh — re-apply immutable flag without breaking the container.
# The DashCaddy container reads /etc/caddy/Caddyfile as a bind mount. chattr +i
# propagates into the container and breaks startup validation. We apply chattr
# +i ONLY when the container is stopped, then unlock before start.sh runs.
#
# SamiPanel is fully purged from this host (cron removed, binaries gone,
# systemd unit masked to /dev/null). The structural protection does not
# depend on the immutable flag; this is defense in depth.

set -e
ACTION="${1:-lock}"

case "$ACTION" in
  unlock)
    chattr -i /etc/caddy/Caddyfile 2>/dev/null || true
    echo "Caddyfile unlocked for container start"
    ;;
  lock)
    # Don't lock if container is running — the bind mount would re-introduce
    # the readonly/immutable state inside the container.
    if docker ps --filter name=dashcaddy-api --format '{{.Names}}' | grep -q dashcaddy-api; then
      echo "DashCaddy container is running — leaving Caddyfile mutable for the bind mount"
    else
      chattr +i /etc/caddy/Caddyfile
      echo "Caddyfile locked (immutable)"
    fi
    ;;
  status)
    lsattr /etc/caddy/Caddyfile | head -1
    ;;
  *)
    echo "Usage: $0 {lock|unlock|status}" >&2
    exit 1
    ;;
esac
