#!/bin/bash
set -euo pipefail

SERVER="http://atb2app1"
LIST_URL="$SERVER/data/attain-api.lst"
TMPDIR="/tmp/attain-api-install"

# Defaults
FORCE=false
TARGET=""
FORCED_PORT=""
DBNAME=""

# ---- Parse parameters ----
while [[ $# -gt 0 ]]; do
    case "$1" in
        -f|--force)
            FORCE=true
            shift
            ;;
        -t|--target)
            TARGET="$2"
            shift 2
            ;;
        -p|--port)
            FORCED_PORT="$2"
            shift 2
            ;;
        -d|--dbname)
            DBNAME="$2"
            shift 2
            ;;
        *)
            echo "Unknown parameter: $1"
            exit 1
            ;;
    esac
done

if [[ -z "$TARGET" ]]; then
    echo "ERROR: --target <sitename> is required."
    exit 1
fi

echo "=== Starting installation for $TARGET ==="

# ---- Fetch latest version from list ----
echo "Fetching version list..."
LATEST=$(curl -fsSL "$LIST_URL" | head -n 1)
if [[ -z "$LATEST" ]]; then
    echo "ERROR: Could not read latest version from attain-api.lst"
    exit 1
fi
echo "Latest version: $LATEST"
ZIP_URL="$SERVER/data/$LATEST"

# ---- Prepare temp folder ----
mkdir -p "$TMPDIR"

# ---- Version check ----
VERSION_FILE="$TMPDIR/.version"
CURRENT_VERSION=""
if [[ -f "$VERSION_FILE" ]]; then
    CURRENT_VERSION=$(cat "$VERSION_FILE")
    if [[ "$CURRENT_VERSION" == "$LATEST" && "$FORCE" == false ]]; then
        echo "Already installed version $CURRENT_VERSION. Use --force to re-install."
    fi
fi

# ---- Download and extract ZIP if needed ----
if [[ ! -f "$TMPDIR/package.zip" || "$FORCE" == true || "$CURRENT_VERSION" != "$LATEST" ]]; then
    echo "Downloading: $ZIP_URL ..."
    curl -fSL "$ZIP_URL" -o "$TMPDIR/package.zip"
    echo "$LATEST" > "$VERSION_FILE"

    echo "Extracting package..."
    rm -rf "$TMPDIR/extracted"
    mkdir -p "$TMPDIR/extracted"
    unzip -qo "$TMPDIR/package.zip" -d "$TMPDIR/extracted"
else
    echo "Using existing extracted files in $TMPDIR/extracted"
fi

# ---- Stop PM2 process if running ----
echo "Stopping PM2 process for $TARGET (if exists)..."
pm2 delete "$TARGET" || true

# ---- Deploy to /var/www/<sitename>.spattain.com ----
TARGET_DIR="/var/www/${TARGET}.spattain.com"
echo "Deploying to: $TARGET_DIR"

if [[ -d "$TARGET_DIR" ]]; then
    echo "Cleaning old deployment..."
    sudo rm -rf "${TARGET_DIR:?}/"*
else
    sudo mkdir -p "$TARGET_DIR"
fi

sudo cp -r "$TMPDIR/extracted/"* "$TARGET_DIR/"
echo "Deployment complete."

# ---- Determine Kestrel port ----
PORT_FILE="$TARGET_DIR/.port"

if [[ -f "$PORT_FILE" ]]; then
    NEXT_PORT=$(cat "$PORT_FILE")
    echo "Existing site detected. Using stored port: $NEXT_PORT"
else
    DEFAULT_PORT=4090
    NEXT_PORT=$DEFAULT_PORT
    MAX_PORT=$((DEFAULT_PORT - 1))
echo "Default port $DEFAULT_PORT"
    if [[ -n "$FORCED_PORT" ]]; then
        NEXT_PORT=$FORCED_PORT
echo "Forced $NEXT_PORT"
    else
echo "Will grep"
USED_PORTS=$(grep -hR "proxy_pass http://localhost:" /etc/nginx/sites-available 2>/dev/null \
             | sed -E 's/^.*proxy_pass http:\/\/localhost:([0-9]+);.*$/\1/' \
             | grep -E '^[0-9]+$' \
             | sort -n || true)
echo "Used ports: $USED_PORTS"
        if [[ -n "$USED_PORTS" ]]; then
            LAST_PORT=$(echo "$USED_PORTS" | tail -n1)
echo "Last port: $LAST_PORT"
            if [[ "$LAST_PORT" =~ ^[0-9]+$ ]]; then
                MAX_PORT=$LAST_PORT
echo "New max port: $MAX_PORT"
            fi
        fi
        NEXT_PORT=$((MAX_PORT + 1))
echo "Next port no old ports $NEXT_PORT"
    fi
    echo "$NEXT_PORT" | sudo tee "$PORT_FILE" > /dev/null
fi
echo "Kestrel port: $NEXT_PORT"

# ---- Ensure /etc/hosts contains local entry ----
HOSTS_LINE="127.0.0.1 ${TARGET}.spattain.com"
if ! grep -qE "127\.0\.0\.1\s+${TARGET}\.spattain\.com" /etc/hosts; then
    echo "Adding hosts entry..."
    echo "$HOSTS_LINE" | sudo tee -a /etc/hosts > /dev/null
    echo "/etc/hosts updated."
else
    echo "/etc/hosts already contains entry."
fi

# ---- Create NGINX config ----
NGINX_CONF="/etc/nginx/sites-available/${TARGET}.spattain.com"
NGINX_LINK="/etc/nginx/sites-enabled/${TARGET}.spattain.com"

if [[ ! -f "$NGINX_CONF" ]]; then
    echo "Creating nginx config: $NGINX_CONF"
    sudo tee "$NGINX_CONF" > /dev/null <<EOF
server {
    listen 4448;
    server_name ${TARGET}.spattain.com;

    location / {
        proxy_pass http://localhost:${NEXT_PORT};
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
    }
}
EOF
else
    echo "NGINX config already exists: $NGINX_CONF"
fi

# ---- Enable site ----
if [[ ! -L "$NGINX_LINK" ]]; then
    echo "Enabling nginx site..."
    sudo ln -s "$NGINX_CONF" "$NGINX_LINK"
else
    echo "Nginx site already enabled."
fi

# ---- Update appsettings.Production.json ----
APPSETTINGS_FILE="$TARGET_DIR/appsettings.Production.json"

if [[ ! -f "$APPSETTINGS_FILE" ]]; then
    echo "ERROR: $APPSETTINGS_FILE not found!"
    exit 1
fi

# Determine db name base
if [[ -n "$DBNAME" ]]; then
    DB_BASE="$DBNAME"
else
    DB_BASE="$TARGET"
fi

echo "Updating appsettings.Production.json..."
TMP_JSON=$(mktemp)

sudo jq \
    --arg instance "$TARGET" \
    --arg port "$NEXT_PORT" \
    --arg db "$DB_BASE" \
    '.Attain.Instance = $instance
     | .Kestrel.Endpoints.Http.Url = "http://localhost:\($port)"
     | .ConnectionStrings.AttainDbContext |= sub("Initial Catalog=[^;]+"; "Initial Catalog=SP_\($db)")
     | .ConnectionStrings.JobsDbContext |= sub("Initial Catalog=[^;]+"; "Initial Catalog=SP_\($db)_jobs")
     | .ConnectionStrings.LogsDbContext |= sub("Initial Catalog=[^;]+"; "Initial Catalog=SP_\($db)_logs")' \
    "$APPSETTINGS_FILE" > "$TMP_JSON"

sudo mv "$TMP_JSON" "$APPSETTINGS_FILE"

echo "appsettings.Production.json updated."

# ---- Fix ecosystem.config.js script entry (convert exe to dll) ----
ECOFILE="$TARGET_DIR/ecosystem.config.js"

if [[ -f "$ECOFILE" ]]; then
    echo "Updating ecosystem.config.js to use dotnet..."
    sudo sed -i 's/script:.*Attain\.Api\.exe"/script: "dotnet Attain.Api.dll"/' "$ECOFILE"
else
    echo "WARNING: No ecosystem.config.js found."
fi

# ---- Start PM2 process ----
echo "Starting PM2 for $TARGET..."
cd "$TARGET_DIR"
pm2 start ecosystem.config.js --only "$TARGET"
pm2 save
echo "PM2 start completed."

# ---- Reload nginx ----
echo "Testing nginx config..."
sudo nginx -t
echo "Reloading nginx..."
sudo systemctl reload nginx

echo "=== Installation for $TARGET completed successfully ==="
echo "Access your site at http://$TARGET.spattain.com (reverse proxy port: 4448 -> localhost:$NEXT_PORT)"
