#!/bin/bash
# Helper Script to set Gitea Repository Secrets
# Usage: ./scripts/setup-gitea-secrets.sh [GITEA_TOKEN]

set -euo pipefail

GITEA_URL="${GITEA_URL:-https://git.michaelschiemer.de}"
REPO_OWNER="${REPO_OWNER:-$(git config user.name || echo 'michael')}"
REPO_NAME="${REPO_NAME:-michaelschiemer}"
GITEA_TOKEN="${1:-${GITEA_TOKEN:-}}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== Gitea Repository Secrets Setup ===${NC}"
echo ""

# Check if token is provided
if [ -z "$GITEA_TOKEN" ]; then
    echo -e "${YELLOW}⚠️  GITEA_TOKEN nicht gesetzt${NC}"
    echo ""
    echo "Bitte generiere einen Gitea Access Token:"
    echo "1. Gehe zu: ${GITEA_URL}/user/settings/applications"
    echo "2. Klicke 'Generate New Token'"
    echo "3. Name: 'secrets-setup'"
    echo "4. Scopes: 'write:repository'"
    echo "5. Kopiere den Token"
    echo ""
    echo "Dann führe aus:"
    echo "  export GITEA_TOKEN='dein-token'"
    echo "  ./scripts/setup-gitea-secrets.sh"
    echo ""
    exit 1
fi

# Function to create/update secret
set_secret() {
    local secret_name=$1
    local secret_value=$2
    
    echo -n "Setting $secret_name... "
    
    # Gitea API endpoint for repository secrets
    local response=$(curl -s -w "\n%{http_code}" \
        -X PUT \
        -H "Authorization: token ${GITEA_TOKEN}" \
        -H "Content-Type: application/json" \
        "${GITEA_URL}/api/v1/repos/${REPO_OWNER}/${REPO_NAME}/actions/secrets/${secret_name}" \
        -d "{
            \"data\": \"${secret_value}\"
        }")
    
    local http_code=$(echo "$response" | tail -n1)
    local body=$(echo "$response" | sed '$d')
    
    if [ "$http_code" = "204" ] || [ "$http_code" = "201" ]; then
        echo -e "${GREEN}✅ OK${NC}"
        return 0
    else
        echo -e "${RED}❌ FAILED (HTTP $http_code)${NC}"
        echo "Response: $body"
        return 1
    fi
}

# Get registry password (default or from vault)
REGISTRY_PASSWORD="${REGISTRY_PASSWORD:-registry-secure-password-2025}"

# Get SSH private key
if [ -f ~/.ssh/production ]; then
    SSH_PRIVATE_KEY=$(cat ~/.ssh/production)
    echo -e "${GREEN}✓ SSH private key gefunden${NC}"
else
    echo -e "${RED}✗ SSH private key nicht gefunden in ~/.ssh/production${NC}"
    echo "Bitte SSH key Pfad anpassen oder manuell setzen"
    exit 1
fi

echo ""
echo "Setting secrets for repository: ${REPO_OWNER}/${REPO_NAME}"
echo ""

# Set secrets
set_secret "REGISTRY_USER" "admin"
set_secret "REGISTRY_PASSWORD" "$REGISTRY_PASSWORD"
set_secret "SSH_PRIVATE_KEY" "$SSH_PRIVATE_KEY"

echo ""
echo -e "${GREEN}=== Secrets Setup Complete ===${NC}"
echo ""
echo "Prüfe Secrets in Gitea UI:"
echo "${GITEA_URL}/${REPO_OWNER}/${REPO_NAME}/enu/repo/settings/secrets"
echo ""
