#!/usr/bin/env bash
# Install config management for Sysadmin Chronicles.
# Config lives at ~/.config/sysadmin-chronicles/config (survives game dir moves).
# Source this file; do not execute directly.

SC_CONFIG_DIR="${SC_CONFIG_DIR:-$HOME/.config/sysadmin-chronicles}"
SC_CONFIG_FILE="$SC_CONFIG_DIR/config"

config_read() {
    [ -f "$SC_CONFIG_FILE" ] && source "$SC_CONFIG_FILE" || true
}

config_write() {
    local key="$1"
    local value="$2"
    mkdir -p "$SC_CONFIG_DIR"
    local tmp
    tmp="$(mktemp "$SC_CONFIG_DIR/config.XXXXXX")"
    if [ -f "$SC_CONFIG_FILE" ]; then
        awk -v key="$key" -v value="$value" '
            BEGIN { found = 0 }
            index($0, key "=") == 1 {
                print key "=" value
                found = 1
                next
            }
            { print }
            END {
                if (!found) {
                    print key "=" value
                }
            }
        ' "$SC_CONFIG_FILE" > "$tmp"
    else
        printf '%s=%s\n' "$key" "$value" > "$tmp"
    fi
    mv "$tmp" "$SC_CONFIG_FILE"
}

config_show() {
    if [ ! -f "$SC_CONFIG_FILE" ]; then
        echo "  (no config file at $SC_CONFIG_FILE)"
        return
    fi
    echo "  Config: $SC_CONFIG_FILE"
    local line key value
    while IFS= read -r line; do
        [[ "$line" =~ ^# ]] && continue
        [[ -z "$line" ]]    && continue
        key="${line%%=*}"
        value="${line#*=}"
        printf '  %-28s %s\n' "$key" "$value"
    done < "$SC_CONFIG_FILE"
}
