#!/usr/bin/env bash
# Create the customer state file and lock file with correct permissions.
# Idempotent. Part of the v109 pivot away from docker label-based dynamic state.
set -euo pipefail

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

mkdir -p /var/lib/whp
chmod 0755 /var/lib/whp

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}"

# Informational: list customer-tier containers that exist
if command -v docker >/dev/null 2>&1; then
    customer_count=$(docker ps -aq --filter label=whp.tier=customer 2>/dev/null | wc -l)
    echo "Found ${customer_count} containers labeled whp.tier=customer"
fi

echo "Customer state file ready."
