#!/usr/bin/env bash
# Seed the customer state file and log which containers exist.
#
# Previous version of this script attempted docker update --label-add to relabel
# existing containers. This fails on plain containers: docker update only supports
# --label-add/rm for Swarm service updates, not standalone containers.
#
# v109 pivot: dynamic state (autostart, disabled_reason, etc.) lives in
# /var/lib/whp/customer-state.json, keyed by container name. This migration
# simply creates that file with correct permissions. No container is recreated.
# The state file starts empty ({}), which means all existing tier=customer
# containers are treated as autostart=true — no behavior change for already-
# running customer sites.
#
# Operators who want a container to participate in the orchestrator sooner
# than its next natural recreation can do so via container-manager.sh.

set -euo pipefail

STATE_FILE=/var/lib/whp/customer-state.json
LOCK_FILE=/var/lib/whp/customer-state.lock

# Create /var/lib/whp if needed
mkdir -p /var/lib/whp
chmod 0755 /var/lib/whp

# Seed state file (idempotent)
if [ ! -f "${STATE_FILE}" ]; then
    echo '{}' > "${STATE_FILE}"
    echo "Created ${STATE_FILE}"
fi
chmod 0640 "${STATE_FILE}"

if [ ! -f "${LOCK_FILE}" ]; then
    touch "${LOCK_FILE}"
    echo "Created ${LOCK_FILE}"
fi
chmod 0640 "${LOCK_FILE}"

echo "--- Customer containers labeled whp.tier=customer ---"
labeled_count=0
while IFS= read -r id; do
    [ -z "${id}" ] && continue
    name="$(docker inspect -f '{{.Name}}' "${id}" 2>/dev/null | sed 's|^/||')"
    echo "  [labeled] ${name} (${id})"
    labeled_count=$((labeled_count + 1))
done < <(docker ps -aq --filter "label=whp.tier=customer" 2>/dev/null)
echo "  Total: ${labeled_count} containers will participate in the boot orchestrator"

echo "--- Containers without whp.tier label (informational) ---"
unlabeled=0
while IFS= read -r id; do
    [ -z "${id}" ] && continue
    tier="$(docker inspect -f '{{ index .Config.Labels "whp.tier" }}' "${id}" 2>/dev/null)"
    if [ -z "${tier}" ]; then
        name="$(docker inspect -f '{{.Name}}' "${id}" 2>/dev/null | sed 's|^/||')"
        echo "  [no-tier] ${name} (${id}) — will NOT participate until recreated"
        unlabeled=$((unlabeled + 1))
    fi
done < <(docker ps -aq 2>/dev/null)
if [ "${unlabeled}" -eq 0 ]; then
    echo "  (none — all containers have whp.tier)"
fi

echo "Customer state file ready. Migration complete."
