#!/bin/bash
# =============================================================================
# update_api_mars_url.sh
# Replaces mars.42gears.com with mars.astrouploads.com in
# appsettings/api/appsettings.json, recreates the api-secret Kubernetes
# secret, and restarts the browserapi-deployment.
# =============================================================================

set -euo pipefail

# ---------------------------------------------------------------------------
# JSON validation helper — uses python3/python (no jq required)
# Works fully offline on any standard Linux system.
# ---------------------------------------------------------------------------
validate_json() {
    local file="$1"
    if command -v python3 &>/dev/null; then
        python3 -c "import sys, json; json.load(open('${file}'))" 2>/dev/null
    elif command -v python &>/dev/null; then
        python -c "import sys, json; json.load(open('${file}'))" 2>/dev/null
    else
        warn "python/python3 not found — skipping JSON validation."
        return 0
    fi
}

# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APPSETTINGS_FILE="${SCRIPT_DIR}/appsettings/api/appsettings.json"
NAMESPACE="suremdm"
SECRET_NAME="api-secret"
DEPLOYMENT_NAME="browserapi-deployment"
LOG_DIR="${SCRIPT_DIR}/logfiles"
LOG_FILE="${LOG_DIR}/update_api_mars_url_$(date '+%Y%m%d_%H%M%S').log"
OLD_HOST="mars.42gears.com"
NEW_HOST="mars.astrouploads.com"

# ---------------------------------------------------------------------------
# Logging helpers
# ---------------------------------------------------------------------------
mkdir -p "${LOG_DIR}"

exec 3>&1                   # fd 3 = real console
exec >> "${LOG_FILE}" 2>&1  # fd 1 & 2 -> log file only

_ts()    { date '+%Y-%m-%d %H:%M:%S'; }
log()    { echo "[$(_ts)] [INFO]  $*"; }
warn()   { echo "[$(_ts)] [WARN]  $*"; }
error()  { echo "[$(_ts)] [ERROR] $*"; }

section() {
    echo ""                                     >&3
    echo "  $*"                                 >&3
    echo "  ------------------------------------------------" >&3
    echo ""
    echo "=== $* ==="
}

ui_ok()   { echo "  [OK]  $*" >&3; log "OK:   $*"; }
ui_info() { echo "  [..]  $*" >&3; log "INFO: $*"; }
ui_fail() { echo "  [!!]  $*" >&3; log "FAIL: $*"; }

# ---------------------------------------------------------------------------
# Startup
# ---------------------------------------------------------------------------
log "Script     : ${BASH_SOURCE[0]}"
log "Log file   : ${LOG_FILE}"
log "Working dir: ${SCRIPT_DIR}"

{
    echo ""
    echo "  +-------------------------------------------------+"
    echo "  |           SureMDM -- System Update              |"
    echo "  +-------------------------------------------------+"
    echo ""
} >&3

# ---------------------------------------------------------------------------
# Silent prerequisite checks
# ---------------------------------------------------------------------------
for cmd in kubectl sed; do
    if ! command -v "$cmd" &>/dev/null; then
        error "Required tool not found: $cmd"
        ui_fail "A required system component is missing. Please contact support."
        exit 1
    fi
    log "Found: $cmd ($(command -v "$cmd"))"
done

if [[ ! -f "${APPSETTINGS_FILE}" ]]; then
    error "appsettings.json not found at: ${APPSETTINGS_FILE}"
    ui_fail "Update prerequisites not met. Please contact support."
    exit 1
fi

if ! kubectl get namespace "${NAMESPACE}" &>/dev/null; then
    error "Kubernetes namespace '${NAMESPACE}' does not exist."
    ui_fail "The application environment is not available. Please contact support."
    exit 1
fi

# ---------------------------------------------------------------------------
# Section 1 — Updating Configuration File
# ---------------------------------------------------------------------------
section "Updating Configuration File"

OCCURRENCES=$(grep -o "${OLD_HOST}" "${APPSETTINGS_FILE}" | wc -l | tr -d '[:space:]' || echo "0")
OCCURRENCES="${OCCURRENCES:-0}"
log "Occurrences of '${OLD_HOST}' found: ${OCCURRENCES}"

if [[ "${OCCURRENCES}" -eq 0 ]]; then
    warn "No occurrences of '${OLD_HOST}' found. Already up to date."
    ui_ok "Configuration is already up to date. No changes required."
else
    BACKUP_FILE="${APPSETTINGS_FILE}.bak.$(date '+%Y%m%d_%H%M%S')"
    cp "${APPSETTINGS_FILE}" "${BACKUP_FILE}"
    log "Backup created: ${BACKUP_FILE}"

    TMP_FILE=$(mktemp)
    sed "s|${OLD_HOST}|${NEW_HOST}|g" "${APPSETTINGS_FILE}" > "${TMP_FILE}"
    mv "${TMP_FILE}" "${APPSETTINGS_FILE}"

    REPLACED=$(grep -o "${NEW_HOST}" "${APPSETTINGS_FILE}" | wc -l | tr -d '[:space:]' || echo "0")
    log "Replacement complete. New occurrences of '${NEW_HOST}': ${REPLACED}"

    if ! validate_json "${APPSETTINGS_FILE}"; then
        error "appsettings.json is not valid JSON after replacement. Restoring backup."
        cp "${BACKUP_FILE}" "${APPSETTINGS_FILE}"
        ui_fail "Configuration update failed. The previous configuration has been restored."
        exit 1
    fi

    ui_ok "Configuration updated successfully."
fi

# ---------------------------------------------------------------------------
# Section 2 — Recreate secret (silent on console)
# ---------------------------------------------------------------------------
log "=== Recreating secret '${SECRET_NAME}' ==="

if kubectl get secret "${SECRET_NAME}" -n "${NAMESPACE}" &>/dev/null; then
    log "Deleting existing secret '${SECRET_NAME}'..."
    kubectl delete secret "${SECRET_NAME}" -n "${NAMESPACE}"
    log "Secret deleted."
else
    log "Secret '${SECRET_NAME}' did not exist — creating fresh."
fi

kubectl create secret generic "${SECRET_NAME}" \
    --from-file="${APPSETTINGS_FILE}" \
    -n "${NAMESPACE}"
log "Secret '${SECRET_NAME}' created."

# ---------------------------------------------------------------------------
# Section 3 — Restarting Application Services
# ---------------------------------------------------------------------------
section "Restarting Application Services"
ui_info "Applying changes. This may take a few minutes."

log "Restarting deployment '${DEPLOYMENT_NAME}'..."
kubectl rollout restart deployment "${DEPLOYMENT_NAME}" -n "${NAMESPACE}" || true

log "Waiting for rollout to complete..."
if kubectl rollout status deployment/"${DEPLOYMENT_NAME}" -n "${NAMESPACE}" --timeout=120s; then
    log "Rollout complete."
    ui_ok "All services have been restarted successfully."
else
    warn "Rollout did not complete within 120s — services may still be starting."
    ui_ok "Services are restarting. They should be ready within a few minutes."
fi

# ---------------------------------------------------------------------------
# Summary
# ---------------------------------------------------------------------------
{
    echo ""
    echo "  +-------------------------------------------------+"
    echo "  |               Update Complete                   |"
    echo "  +-------------------------------------------------+"
    echo ""
    echo "  The system has been updated and all services are"
    echo "  running with the latest configuration."
    echo ""
} >&3

log "Script completed successfully."
