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

# ── Configuration ──────────────────────────────────────────────
REGISTRY="gitea.nerdboden.de"
OWNER="thefurya"
IMAGES=("nuzlocke-tracker-api" "nuzlocke-tracker-frontend")
DOCKERFILES=("backend/Dockerfile.prod" "frontend/Dockerfile.prod")
CONTEXTS=("./backend" "./frontend")

if command -v podman &>/dev/null; then
    CONTAINER_CMD="podman"
elif command -v docker &>/dev/null; then
    CONTAINER_CMD="docker"
else
    echo "Neither podman nor docker found." >&2; exit 1
fi

UNRAID_SSH="root@192.168.1.10"
UNRAID_DEPLOY_DIR="/mnt/user/appdata/nuzlocke-tracker"

# ── Helpers ────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

info()  { echo -e "${GREEN}[✓]${NC} $1"; }
warn()  { echo -e "${YELLOW}[!]${NC} $1"; }
error() { echo -e "${RED}[✗]${NC} $1"; exit 1; }

# ── Preflight checks ──────────────────────────────────────────
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [[ "$BRANCH" != "main" ]]; then
    warn "You are on branch '$BRANCH', not 'main'."
    read -rp "Continue anyway? [y/N] " confirm
    [[ "$confirm" =~ ^[Yy]$ ]] || exit 0
fi

if ! git diff --quiet || ! git diff --cached --quiet; then
    warn "You have uncommitted changes."
    read -rp "Continue anyway? [y/N] " confirm
    [[ "$confirm" =~ ^[Yy]$ ]] || exit 0
fi

# ── Build and push images ─────────────────────────────────────
for i in "${!IMAGES[@]}"; do
    IMAGE="${REGISTRY}/${OWNER}/${IMAGES[$i]}:latest"
    info "Building ${IMAGES[$i]}..."
    $CONTAINER_CMD build --platform linux/amd64 -t "$IMAGE" -f "${DOCKERFILES[$i]}" "${CONTEXTS[$i]}"
    info "Pushing ${IMAGES[$i]}..."
    $CONTAINER_CMD push "$IMAGE"
done

info "All images built and pushed."

# ── Sync compose file to Unraid ──────────────────────────────────
info "Copying docker-compose.prod.yml to Unraid..."
scp docker-compose.prod.yml "${UNRAID_SSH}:${UNRAID_DEPLOY_DIR}/docker-compose.yml" \
    || error "Failed to copy compose file to Unraid."
info "Compose file synced."

# ── Ensure .env with Postgres password exists ────────────────────
info "Checking for .env on Unraid..."
ssh "${UNRAID_SSH}" "
    if [ ! -f '${UNRAID_DEPLOY_DIR}/.env' ]; then
        PASS=\$(head -c 32 /dev/urandom | base64 | tr -dc 'A-Za-z0-9' | head -c 32)
        echo \"POSTGRES_PASSWORD=\${PASS}\" > '${UNRAID_DEPLOY_DIR}/.env'
        echo 'Generated new .env with POSTGRES_PASSWORD'
    else
        echo '.env already exists, skipping'
    fi
" || error "Failed to check/create .env on Unraid."

# ── Pull images and (re)start on Unraid ──────────────────────────
info "Pulling images and starting containers on Unraid..."
ssh "${UNRAID_SSH}" "cd '${UNRAID_DEPLOY_DIR}' && docker compose pull && docker compose up -d" \
    || error "Failed to start containers on Unraid."

info "Deploy complete!"
