#!/bin/bash
# Setup Gitea Admin Secret and Initialize Gitea
#
# This script:
# 1. Creates gitea-admin-secret (gitea namespace) - Used by Gitea Helm chart for admin credentials
# 2. Creates gitea-registry-secret (bakery-ia namespace) - Used by pods for imagePullSecrets
# 3. Applies the gitea-init-job.yaml to create the initial repository
#
# Usage:
#   Development:
#     ./setup-admin-secret.sh                    # Uses default dev password
#     ./setup-admin-secret.sh [password]         # Uses provided password
#     ./setup-admin-secret.sh --secrets-only     # Only create secrets, skip init job
#
#   Production:
#     export GITEA_ADMIN_PASSWORD=$(openssl rand -base64 32)
#     ./setup-admin-secret.sh --production
#     ./setup-admin-secret.sh --production --secrets-only
#
# Environment variables:
#   GITEA_ADMIN_PASSWORD - Password to use (required for --production)

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
KUBECTL="kubectl"
GITEA_NAMESPACE="gitea"
BAKERY_NAMESPACE="bakery-ia"
REGISTRY_HOST="registry.bakery-ia.local"
ADMIN_USERNAME="bakery-admin"
# Default password for dev environment only
# For PRODUCTION: Always set GITEA_ADMIN_PASSWORD environment variable
# Generate secure password with: openssl rand -base64 32
DEV_DEFAULT_PASSWORD="pvYUkGWJijqc0QfIZEXw"
SECRETS_ONLY=false
IS_PRODUCTION=false

# Check if running in microk8s
if command -v microk8s &> /dev/null; then
    KUBECTL="microk8s kubectl"
fi

# Parse arguments
for arg in "$@"; do
    case $arg in
        --secrets-only)
            SECRETS_ONLY=true
            ;;
        --production)
            IS_PRODUCTION=true
            REGISTRY_HOST="registry.bakewise.ai"
            ;;
        *)
            if [ -z "$ADMIN_PASSWORD" ] && [ "$arg" != "--secrets-only" ] && [ "$arg" != "--production" ]; then
                ADMIN_PASSWORD="$arg"
            fi
            ;;
    esac
done

# Get password from argument, environment variable, or use default (dev only)
if [ -z "$ADMIN_PASSWORD" ]; then
    if [ -n "$GITEA_ADMIN_PASSWORD" ]; then
        ADMIN_PASSWORD="$GITEA_ADMIN_PASSWORD"
        echo "Using password from GITEA_ADMIN_PASSWORD environment variable"
    elif [ "$IS_PRODUCTION" = true ]; then
        echo "ERROR: Production deployment requires GITEA_ADMIN_PASSWORD environment variable"
        echo "Generate a secure password with: openssl rand -base64 32"
        echo ""
        echo "Usage for production:"
        echo "  export GITEA_ADMIN_PASSWORD=\$(openssl rand -base64 32)"
        echo "  ./setup-admin-secret.sh --production"
        exit 1
    else
        ADMIN_PASSWORD="$DEV_DEFAULT_PASSWORD"
        echo "WARNING: Using default dev password. For production, set GITEA_ADMIN_PASSWORD"
    fi
fi

# Validate password strength for production
if [ "$IS_PRODUCTION" = true ] && [ ${#ADMIN_PASSWORD} -lt 16 ]; then
    echo "ERROR: Production password must be at least 16 characters"
    exit 1
fi

# Create namespaces if they don't exist
$KUBECTL create namespace "$GITEA_NAMESPACE" --dry-run=client -o yaml | $KUBECTL apply -f -
$KUBECTL create namespace "$BAKERY_NAMESPACE" --dry-run=client -o yaml | $KUBECTL apply -f -

# 1. Create gitea-admin-secret for Gitea Helm chart
echo "Creating gitea-admin-secret in $GITEA_NAMESPACE namespace..."
$KUBECTL create secret generic gitea-admin-secret \
    --namespace "$GITEA_NAMESPACE" \
    --from-literal=username="$ADMIN_USERNAME" \
    --from-literal=password="$ADMIN_PASSWORD" \
    --dry-run=client -o yaml | $KUBECTL apply -f -

# 2. Create gitea-registry-secret for imagePullSecrets
echo "Creating gitea-registry-secret in $BAKERY_NAMESPACE namespace..."

# Create Docker config JSON for registry authentication
# Include both external (ingress) and internal (cluster) registry URLs
AUTH_BASE64=$(echo -n "${ADMIN_USERNAME}:${ADMIN_PASSWORD}" | base64)
INTERNAL_REGISTRY_HOST="gitea-http.gitea.svc.cluster.local:3000"
DOCKER_CONFIG_JSON=$(cat <<EOF
{
  "auths": {
    "${REGISTRY_HOST}": {
      "username": "${ADMIN_USERNAME}",
      "password": "${ADMIN_PASSWORD}",
      "auth": "${AUTH_BASE64}"
    },
    "${INTERNAL_REGISTRY_HOST}": {
      "username": "${ADMIN_USERNAME}",
      "password": "${ADMIN_PASSWORD}",
      "auth": "${AUTH_BASE64}"
    }
  }
}
EOF
)

# Base64 encode the entire config (use -w0 on Linux, no flag needed on macOS)
if [[ "$OSTYPE" == "darwin"* ]]; then
    DOCKER_CONFIG_BASE64=$(echo -n "$DOCKER_CONFIG_JSON" | base64)
else
    DOCKER_CONFIG_BASE64=$(echo -n "$DOCKER_CONFIG_JSON" | base64 -w0)
fi

# Create the registry secret
cat <<EOF | $KUBECTL apply -f -
apiVersion: v1
kind: Secret
metadata:
  name: gitea-registry-secret
  namespace: ${BAKERY_NAMESPACE}
  labels:
    app.kubernetes.io/name: bakery-ia
    app.kubernetes.io/component: registry
    app.kubernetes.io/managed-by: setup-admin-secret
type: kubernetes.io/dockerconfigjson
data:
  .dockerconfigjson: ${DOCKER_CONFIG_BASE64}
EOF

echo ""
echo "=========================================="
echo "Gitea secrets created successfully!"
echo "=========================================="
echo ""
echo "Environment: $([ "$IS_PRODUCTION" = true ] && echo "PRODUCTION" || echo "Development")"
echo ""
echo "Credentials:"
echo "  Username: $ADMIN_USERNAME"
if [ "$IS_PRODUCTION" = true ]; then
    echo "  Password: (stored in secret, not displayed for security)"
else
    echo "  Password: $ADMIN_PASSWORD"
fi
echo ""
echo "Secrets created:"
echo "  1. gitea-admin-secret      (namespace: $GITEA_NAMESPACE)  - For Gitea Helm chart"
echo "  2. gitea-registry-secret   (namespace: $BAKERY_NAMESPACE) - For imagePullSecrets"
echo ""
echo "Registry URLs:"
echo "  External: https://$REGISTRY_HOST"
echo "  Internal: $INTERNAL_REGISTRY_HOST"
echo ""

# Apply the init job ConfigMap and Job (but Job won't run until Gitea is installed)
if [ "$SECRETS_ONLY" = false ]; then
    INIT_JOB_FILE="$SCRIPT_DIR/gitea-init-job.yaml"
    if [ -f "$INIT_JOB_FILE" ]; then
        echo "Applying Gitea initialization resources..."
        $KUBECTL apply -f "$INIT_JOB_FILE"
        echo ""
        echo "Init job will create the 'bakery-ia' repository once Gitea is ready."
    else
        echo "Warning: gitea-init-job.yaml not found at $INIT_JOB_FILE"
    fi
    echo ""
fi

echo "Next steps:"
if [ "$IS_PRODUCTION" = true ]; then
    echo "  1. Install Gitea for production:"
    echo "     helm upgrade --install gitea gitea/gitea -n gitea \\"
    echo "       -f infrastructure/cicd/gitea/values.yaml \\"
    echo "       -f infrastructure/cicd/gitea/values-prod.yaml"
    echo ""
    echo "  2. Install Tekton CI/CD for production:"
    echo "     export TEKTON_WEBHOOK_TOKEN=\$(openssl rand -hex 32)"
    echo "     helm upgrade --install tekton-cicd infrastructure/cicd/tekton-helm \\"
    echo "       -n tekton-pipelines \\"
    echo "       -f infrastructure/cicd/tekton-helm/values.yaml \\"
    echo "       -f infrastructure/cicd/tekton-helm/values-prod.yaml \\"
    echo "       --set secrets.webhook.token=\$TEKTON_WEBHOOK_TOKEN \\"
    echo "       --set secrets.registry.password=\$GITEA_ADMIN_PASSWORD \\"
    echo "       --set secrets.git.password=\$GITEA_ADMIN_PASSWORD"
else
    echo "  1. Install Gitea (if not already installed):"
    echo "     helm install gitea gitea/gitea -n gitea -f infrastructure/cicd/gitea/values.yaml"
fi
echo ""
echo "  $([ "$IS_PRODUCTION" = true ] && echo "3" || echo "2"). Wait for Gitea to be ready:"
echo "     kubectl wait --for=condition=ready pod -n gitea -l app.kubernetes.io/name=gitea --timeout=300s"
echo ""
echo "  $([ "$IS_PRODUCTION" = true ] && echo "4" || echo "3"). Check init job status:"
echo "     kubectl logs -n gitea -l app.kubernetes.io/component=init --tail=50"
