#!/usr/bin/env bash

# Deploy Hyperledger Firefly
# This script deploys Firefly to Kubernetes

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

# Configuration
NAMESPACE="${NAMESPACE:-firefly}"
BESU_RPC_URL="${BESU_RPC_URL:-http://besu-rpc-service.besu-network.svc.cluster.local:8545}"
BESU_WS_URL="${BESU_WS_URL:-ws://besu-rpc-service.besu-network.svc.cluster.local:8546}"
CHAIN_ID="${CHAIN_ID:-138}"


log_success "Deploying Hyperledger Firefly..."

# Check prerequisites
if ! command -v kubectl &> /dev/null; then
    log_error "Error: kubectl not found"
    exit 1
fi

# Create namespace
log_warn "Creating namespace..."
kubectl apply -f "$PROJECT_ROOT/k8s/firefly/namespace.yaml"

# Create secrets
log_warn "Creating secrets..."
kubectl apply -f "$PROJECT_ROOT/k8s/firefly/secrets.yaml"

# Update ConfigMap with Besu RPC URLs
log_warn "Updating ConfigMap..."
kubectl create configmap firefly-config \
    --from-file="$PROJECT_ROOT/k8s/firefly/configmap.yaml" \
    --namespace="$NAMESPACE" \
    --dry-run=client -o yaml | kubectl apply -f -

# Deploy PostgreSQL
log_warn "Deploying PostgreSQL..."
kubectl apply -f "$PROJECT_ROOT/k8s/firefly/postgres.yaml"

# Wait for PostgreSQL to be ready
log_warn "Waiting for PostgreSQL to be ready..."
kubectl wait --for=condition=ready pod -l app=firefly-postgres -n "$NAMESPACE" --timeout=300s

# Deploy IPFS
log_warn "Deploying IPFS..."
kubectl apply -f "$PROJECT_ROOT/k8s/firefly/ipfs.yaml"

# Wait for IPFS to be ready
log_warn "Waiting for IPFS to be ready..."
kubectl wait --for=condition=ready pod -l app=firefly-ipfs -n "$NAMESPACE" --timeout=300s

# Deploy Firefly Core
log_warn "Deploying Firefly Core..."
kubectl apply -f "$PROJECT_ROOT/k8s/firefly/firefly-core.yaml"

# Wait for Firefly to be ready
log_warn "Waiting for Firefly to be ready..."
kubectl wait --for=condition=ready pod -l app=firefly-core -n "$NAMESPACE" --timeout=300s

log_success "Firefly deployed successfully!"
log_warn "Firefly API: http://firefly-api.$NAMESPACE.svc.cluster.local:5000"

