#!/usr/bin/env bash
set -euo pipefail

# ======= CONFIGURATION =======
NAMESPACE="ef-external"
SECRET_NAME="mongo-mongodb-ca"
MONGO_HOST="mongo-mongodb.ef-external.svc.cluster.local"
MONGO_PORT=27017
MONGO_DB="cim-tenant"
MONGO_COLLECTION="tenants"
MONGO_USER="root"
MONGO_PASS="Expertflow123"
CERT_DIR="/tmp/mongodb_certs_$$" 
JSON_TEMPLATE="cim-tenant.tenants.json"
JSON_OUTPUT="/tmp/cim-tenant.tenants.json.substituted_$$"

MINIO_URL="https://minio.ef-external.svc.cluster.local:9000"
MINIO_SECRET_NAME="minio" 
MINIO_DEFAULT_BUCKET="default"  
MINIO_HELPER_POD_NAME="minio-helper"

# Define some colors for logging
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# ======= CLEANUP FUNCTION AND TRAP =======
# This function is guaranteed to run when the script exits,
# ensuring the pod and temp files are always removed.
cleanup() {
  # Check if the last command failed. '$?' holds the exit code.
  if [ "$?" -ne 0 ]; then
      echo -e "${RED}[FAILED] An error occurred. Script is halting.${NC}"
  fi
  echo "[INFO] Cleaning up resources..."
  # The '|| true' prevents the trap from exiting with an error if the pod is already gone.
  kubectl delete pod mongo-tools -n "$NAMESPACE" --ignore-not-found=true --now > /dev/null 2>&1 || true
  kubectl delete pod minio-helper -n "$NAMESPACE" --ignore-not-found=true --now > /dev/null 2>&1 || true
  rm -rf "$CERT_DIR" "$JSON_OUTPUT"
}
trap cleanup EXIT

# ======= INPUTS =======
tenantId=${1:?Usage: ./import_tenant.sh <tenantId> <fqdn>}
FQDN=${2:?Usage: ./import_tenant.sh <tenantId> <fqdn>}

# ======= SCRIPT LOGIC =======
echo "[INFO] Starting import for tenant: ${tenantId}"

# 1. Generate a random tenant code and substitute variables
TENANT_CODE=$RANDOM
echo "[INFO] 1/7: Generating tenant configuration..."
sed -e "s|\${tenantId}|${tenantId}|g" \
    -e "s|\${FQDN}|${FQDN}|g" \
    -e "s|\${TENANT_CODE}|${TENANT_CODE}|g" \
    < "$JSON_TEMPLATE" > "$JSON_OUTPUT"

# 2. Prepare certs
echo "[INFO] 2/7: Extracting MongoDB certificates..."
mkdir -p "$CERT_DIR"
kubectl get secret "$SECRET_NAME" -n "$NAMESPACE" -o go-template='{{range $k,$v := .data}}{{$k}}{{"\n"}}{{$v}}{{"\n"}}{{end}}' | while read -r key && read -r value; do
    echo "$value" | tr -d '\r' | base64 --decode > "$CERT_DIR/$key"
done
if [ ! -f "$CERT_DIR/mongodb-ca-cert" ] || [ ! -f "$CERT_DIR/client-pem" ]; then
    echo -e "${RED}[FATAL] Expected cert files ('mongodb-ca-cert', 'client-pem') not found in secret.${NC}" >&2
    exit 1
fi

# 3. Create mongo-tools pod
echo "[INFO] 3/7: Creating temporary pod for import..."
kubectl -n "$NAMESPACE" run mongo-tools --image=mongo:6.0 --restart=Never --command -- sleep 3600 > /dev/null
kubectl wait --for=condition=Ready pod/mongo-tools -n "$NAMESPACE" --timeout=120s > /dev/null

# 4. Copy files
echo "[INFO] 4/7: Copying files to pod..."
kubectl -n "$NAMESPACE" cp "$JSON_OUTPUT" mongo-tools:/tmp/cim-tenant.tenants.json > /dev/null
kubectl -n "$NAMESPACE" cp "$CERT_DIR/mongodb-ca-cert" mongo-tools:/tmp/mongodb-ca-cert > /dev/null
kubectl -n "$NAMESPACE" cp "$CERT_DIR/client-pem" mongo-tools:/tmp/combined.pem > /dev/null

# 5. Import data
echo "[INFO] 5/7: Importing data into MongoDB..."
# We let the output of mongoimport show, as it's meaningful (e.g., "1 document(s) imported successfully").
kubectl -n "$NAMESPACE" exec mongo-tools -- \
  mongoimport \
  --host "$MONGO_HOST" \
  --port "$MONGO_PORT" \
  --db "$MONGO_DB" \
  --collection "$MONGO_COLLECTION" \
  --file /tmp/cim-tenant.tenants.json \
  --jsonArray \
  --ssl \
  --sslCAFile /tmp/mongodb-ca-cert \
  --sslPEMKeyFile /tmp/combined.pem \
  --username "$MONGO_USER" \
  --password "$MONGO_PASS" \
  --authenticationDatabase admin

# Final success message
echo -e "\n${GREEN}[SUCCESS] Tenant '$tenantId' imported successfully!${NC}"

# ======= MINIO OPERATIONS =======

# 4. Prepare MinIO client
echo "[INFO] 6/7: Preparing MinIO client..."

MINIO_ACCESS_KEY=$(kubectl get secret $MINIO_SECRET_NAME -n $NAMESPACE -o jsonpath='{.data.root-user}' | base64 --decode)
MINIO_SECRET_KEY=$(kubectl get secret $MINIO_SECRET_NAME -n $NAMESPACE -o jsonpath='{.data.root-password}' | base64 --decode)

echo "       -> Creating MinIO helper pod..."
kubectl -n "$NAMESPACE" run "$MINIO_HELPER_POD_NAME" --image=minio/mc --restart=Never --command -- sleep 3600 > /dev/null
kubectl wait --for=condition=Ready pod/"$MINIO_HELPER_POD_NAME" -n "$NAMESPACE" --timeout=120s > /dev/null

echo "       -> Configuring MinIO client alias..."
kubectl -n "$NAMESPACE" exec "$MINIO_HELPER_POD_NAME" -- mc alias set minio "$MINIO_URL" "$MINIO_ACCESS_KEY" "$MINIO_SECRET_KEY" --api S3v4 --insecure > /dev/null

# 5. Create tenant bucket and copy assets
echo "[INFO] 7/7: Creating bucket for '$tenantId' and copying assets..."
echo "       -> Verifying that the default bucket exists..."
if ! kubectl -n "$NAMESPACE" exec "$MINIO_HELPER_POD_NAME" -- mc ls minio/"$MINIO_DEFAULT_BUCKET" --insecure > /dev/null 2>&1; then
    echo -e "${RED}[FATAL] The source bucket '$MINIO_DEFAULT_BUCKET' does not exist. Cannot copy assets.${NC}" >&2
    exit 1
fi

echo "       -> Creating new bucket '$tenantId'..."
kubectl -n "$NAMESPACE" exec "$MINIO_HELPER_POD_NAME" -- mc mb minio/"$tenantId" --insecure

echo "       -> Copying assets from '$MINIO_DEFAULT_BUCKET'..."
kubectl -n "$NAMESPACE" exec "$MINIO_HELPER_POD_NAME" -- mc cp --recursive --insecure minio/"$MINIO_DEFAULT_BUCKET"/ minio/"$tenantId"/

# ======= FINAL SUCCESS =======
echo -e "\n${GREEN}[SUCCESS] Tenant '$tenantId' fully onboarded!${NC}"
