#!/bin/bash
# ==============================================================================================
# deploy.sh — Sync dev working tree → prod runtime for Plugin PHP and conf files.
# ==============================================================================================
#
# Direct call (interactive):  ! bash Deployment/deploy.sh
#   Deploys both Plugin and Configurations with full output.
#
# Hook call (Claude Code PostToolUse):
#   Reads the tool JSON from stdin, deploys only the component that was actually changed.
#   Plugin/  → rsync --delete into prod Plugin/unraid/
#   Configurations/ → conf_upgrade.sh (adds new keys, preserves prod values)
#
# ==============================================================================================

DEV_ROOT="/mnt/cloud-storage/Important Shit/Git/Development/Varaverk"
PROD_ROOT="/mnt/user/appdata/Varaverk"
UPGRADE="$PROD_ROOT/Deployment/conf_upgrade.sh"
LOG="/tmp/vv_deploy.log"

# ── Deploy functions ──────────────────────────────────────────────────────────

deploy_plugin() {
    rsync -a --delete --exclude='.git' \
        "$DEV_ROOT/Plugin/unraid/" \
        "$PROD_ROOT/Plugin/unraid/"
}

deploy_conf() {
    for conf in master.conf host1.conf host2.conf; do
        tmpl="$DEV_ROOT/Configurations/$conf"
        target="$PROD_ROOT/Configurations/$conf"
        [[ -f "$tmpl" && -f "$target" ]] && \
            "$UPGRADE" --template "$tmpl" --target "$target"
    done
}

# ── Entry point ───────────────────────────────────────────────────────────────

# Read stdin (non-blocking — empty when called directly or via '!')
STDIN=$(cat 2>/dev/null || true)

# Extract file_path from hook JSON if present
FILE=$(python3 -c "
import json, sys
try:
    d = json.loads(sys.stdin.read())
    print(d.get('tool_input', {}).get('file_path', ''))
except:
    print('')
" <<< "$STDIN" 2>/dev/null || echo "")

if [[ -z "$FILE" ]]; then
    # Direct call (interactive or via !) — deploy everything with output
    echo "=== deploy: dev → prod ==="
    echo ""
    echo "── Plugin ──"
    deploy_plugin && echo "  rsync done"
    echo ""
    echo "── Configurations ──"
    deploy_conf
    echo ""
    echo "=== done ==="
    exit 0
fi

# Hook call — deploy only the affected component, log silently
{
    echo "[$(date '+%H:%M:%S')] hook: $FILE"

    if [[ "$FILE" == "$DEV_ROOT/Plugin/"* ]]; then
        deploy_plugin && echo "  plugin synced"
    fi

    if [[ "$FILE" == "$DEV_ROOT/Configurations/"* ]]; then
        deploy_conf && echo "  conf upgraded"
    fi
} >> "$LOG" 2>&1

exit 0
