#!/usr/bin/env bash
# Customer container state file helpers. Sourced, not executed.
# Single source of truth for autostart / disabled state for customer containers.

WHP_STATE_FILE="${WHP_STATE_FILE:-/var/lib/whp/customer-state.json}"
WHP_STATE_LOCK="${WHP_STATE_LOCK:-/var/lib/whp/customer-state.lock}"

# Ensure state file + lock exist with sane perms. Safe to call repeatedly.
whp_state_init() {
    local dir; dir="$(dirname "${WHP_STATE_FILE}")"
    mkdir -p "${dir}"
    chmod 0755 "${dir}"
    [ -f "${WHP_STATE_FILE}" ] || echo '{}' > "${WHP_STATE_FILE}"
    chmod 0640 "${WHP_STATE_FILE}"
    [ -f "${WHP_STATE_LOCK}" ] || touch "${WHP_STATE_LOCK}"
    chmod 0640 "${WHP_STATE_LOCK}"
}

# Read autostart for a container. Default true if container not in file.
# Echoes "true" or "false".
whp_state_autostart() {
    local name="$1"
    if ! command -v jq >/dev/null 2>&1; then echo "true"; return; fi
    [ -f "${WHP_STATE_FILE}" ] || { echo "true"; return; }
    local v
    # NOTE: cannot use `// true` here — jq's alternative operator treats both
    # null AND false as "alternative needed", so `.autostart // true` would
    # return `true` for an explicit `false`. Use explicit comparison instead.
    v="$(jq -r --arg n "$name" 'if .[$n].autostart == false then "false" else "true" end' "${WHP_STATE_FILE}" 2>/dev/null)"
    case "${v}" in true) echo "true";; false) echo "false";; *) echo "true";; esac
}

# Filter a stream of container names, emitting only those with autostart=true.
# Reads names on stdin, one per line. Writes filtered names on stdout.
whp_state_filter_autostart() {
    while IFS= read -r name; do
        [ -z "${name}" ] && continue
        if [ "$(whp_state_autostart "${name}")" = "true" ]; then
            echo "${name}"
        fi
    done
}
