#!/bin/bash
set -e

YAML_FILE="proxmox-infra/Pulumi.dev.yaml"

# Load local env if present
if [ -f .env.local ]; then
  export $(grep -v '^#' .env.local | xargs)
fi

if [ ! -f "$YAML_FILE" ]; then
  echo "[pre-push] $YAML_FILE not found — skipping Gitea secret sync"
  exit 0
fi

if [ -z "$GITEA_API_URL" ] || [ -z "$GITEA_TOKEN" ]; then
  echo "[pre-push] GITEA_API_URL or GITEA_TOKEN not set — skipping Gitea secret sync"
  echo "[pre-push] Add these to .env.local to enable automatic sync"
  exit 0
fi

ENCODED=$(base64 -w 0 "$YAML_FILE")

HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X PUT \
  -H "Authorization: token $GITEA_TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"data\": \"$ENCODED\"}" \
  "$GITEA_API_URL/actions/secrets/PULUMI_DEV_YAML")

if [ "$HTTP_STATUS" = "201" ] || [ "$HTTP_STATUS" = "204" ]; then
  echo "[pre-push] Gitea secret PULUMI_DEV_YAML updated"
else
  echo "[pre-push] Failed to update Gitea secret (HTTP $HTTP_STATUS)"
  echo "[pre-push] Check GITEA_API_URL and GITEA_TOKEN in .env.local"
  exit 1
fi
