#!/bin/bash
set -euo pipefail

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

FORCE=false
TARGET=""

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

echo "=== Starting installation ==="

# ---- Fetch attain-api.lst ----
echo "Fetching list from $LIST_URL ..."
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 available: $LATEST"

ZIP_URL="$SERVER/data/$LATEST"

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

# ---- Check .version ----
if [[ -f "$VERSION_FILE" ]]; then
    CURRENT_VERSION=$(cat "$VERSION_FILE")
    if [[ "$CURRENT_VERSION" == "$LATEST" && "$FORCE" == false ]]; then
        echo "The current installed version ($CURRENT_VERSION) is already up to date."
        echo "Use --force to reinstall."
        exit 0
    fi
fi

# ---- Download ZIP ----
echo "Downloading: $ZIP_URL ..."
curl -fSL "$ZIP_URL" -o "$TMPDIR/package.zip"

echo "$LATEST" > "$VERSION_FILE"
echo "Version marker updated: $VERSION_FILE"

# ---- Extract ----
echo "Extracting package..."
rm -rf "$TMPDIR/extracted"
mkdir -p "$TMPDIR/extracted"

unzip -qo "$TMPDIR/package.zip" -d "$TMPDIR/extracted"

echo "Package extracted."

# ---- If no target specified, stop here ----
if [[ -z "$TARGET" ]]; then
    echo "No --target specified. Extraction complete, stopping."
    exit 0
fi

# ---- Deployment ----
TARGET_DIR="/var/www/${TARGET}.spattain.com"
NGINX_CONF="/etc/nginx/sites-available/${TARGET}.spattain.com"
NGINX_LINK="/etc/nginx/sites-enabled/${TARGET}.spattain.com"

echo "Deploying to: $TARGET_DIR"

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

echo "Copying new files..."
sudo cp -r "$TMPDIR/extracted/"* "$TARGET_DIR/"

echo "Files copied to $TARGET_DIR"

echo "Deployment complete."

# ---- Ensure /etc/hosts has the local entry ----
HOSTS_LINE="127.0.0.1 ${TARGET}.spattain.com"

echo "Checking /etc/hosts for ${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 the entry."
fi

# ---- Create nginx configuration if needed ----
if [[ ! -f "$NGINX_CONF" ]]; then
    echo "Creating nginx config: $NGINX_CONF"

    sudo tee "$NGINX_CONF" >/dev/null <<EOF
server {
    listen 80;
    server_name ${TARGET}.spattain.com;

    root $TARGET_DIR;
    index index.html index.htm;

    autoindex on;

    location / {
        try_files \$uri \$uri/ =404;
    }
}
EOF

    echo "Nginx site created."
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

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

echo "=== Installation completed successfully ==="
