#!/bin/bash

# Update NPMplus to 2026-01-20-r2
# Run this script on Proxmox host (r630-01) - it uses pct exec to run Docker commands in LXC container
# Usage: ssh root@r630-01 'bash' < update-npmplus-direct.sh

set -euo pipefail

LXC_CONTAINER="10233"
DOCKER_CONTAINER="npmplus"
NEW_IMAGE="zoeyvid/npmplus:2026-01-20-r2"
BACKUP_DIR="/data/npmplus-backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

echo "=========================================="
echo "Update NPMplus to 2026-01-20-r2"
echo "=========================================="
echo ""

# Step 1: Check current version
echo "Step 1: Checking current version..."
CURRENT_IMAGE=$(pct exec $LXC_CONTAINER -- docker inspect $DOCKER_CONTAINER --format '{{.Config.Image}}' 2>/dev/null || echo "not found")
echo "Current: $CURRENT_IMAGE"

if echo "$CURRENT_IMAGE" | grep -q "2026-01-20-r2"; then
    echo "✅ Already running 2026-01-20-r2"
    exit 0
fi

# Step 2: Create backup
echo ""
echo "Step 2: Creating backup..."
mkdir -p "$BACKUP_DIR"
pct exec $LXC_CONTAINER -- docker exec $DOCKER_CONTAINER tar -czf /tmp/npmplus-backup-${TIMESTAMP}.tar.gz -C /data . 2>/dev/null || echo "Backup warning"
pct exec $LXC_CONTAINER -- docker cp $DOCKER_CONTAINER:/tmp/npmplus-backup-${TIMESTAMP}.tar.gz /tmp/ 2>/dev/null || echo "Backup copy warning"
pct exec $LXC_CONTAINER -- docker exec $DOCKER_CONTAINER rm -f /tmp/npmplus-backup-*.tar.gz 2>/dev/null || true
# Copy from container to host
pct exec $LXC_CONTAINER -- cp /tmp/npmplus-backup-${TIMESTAMP}.tar.gz "$BACKUP_DIR/" 2>/dev/null || echo "Final copy warning"

if [ -f "$BACKUP_DIR/npmplus-backup-${TIMESTAMP}.tar.gz" ]; then
    echo "✅ Backup created: $BACKUP_DIR/npmplus-backup-${TIMESTAMP}.tar.gz"
else
    echo "⚠️  Backup may have failed, but continuing (volumes are preserved)"
fi

# Step 3: Pull new image
echo ""
echo "Step 3: Pulling new image (this may take 2-5 minutes)..."
echo "Note: If this times out, the image will be pulled when creating the container"
pct exec $LXC_CONTAINER -- timeout 180 docker pull $NEW_IMAGE 2>&1 | tail -5 || echo "Pull timeout (will retry during container creation)"

# Step 4: Stop container
echo ""
echo "Step 4: Stopping container..."
pct exec $LXC_CONTAINER -- docker stop $DOCKER_CONTAINER

# Step 5: Get volume mounts
echo ""
echo "Step 5: Getting volume configuration..."
VOLUMES=$(pct exec $LXC_CONTAINER -- docker inspect $DOCKER_CONTAINER --format '{{range .Mounts}}-v {{.Source}}:{{.Destination}} {{end}}' 2>/dev/null || echo "-v /data/npmplus:/data -v /data/letsencrypt:/etc/letsencrypt")
echo "Volumes: $VOLUMES"

# Step 6: Remove old container
echo ""
echo "Step 6: Removing old container..."
pct exec $LXC_CONTAINER -- docker rm $DOCKER_CONTAINER

# Step 7: Create new container
echo ""
echo "Step 7: Creating new container..."
pct exec $LXC_CONTAINER -- docker run -d \
  --name $DOCKER_CONTAINER \
  --restart unless-stopped \
  --network bridge \
  -p 80:80 \
  -p 443:443 \
  -p 81:81 \
  $VOLUMES \
  $NEW_IMAGE

# Step 8: Verify
echo ""
echo "Step 8: Verifying..."
sleep 10
pct exec $LXC_CONTAINER -- docker ps --filter name=$DOCKER_CONTAINER

NEW_VERSION=$(pct exec $LXC_CONTAINER -- docker inspect $DOCKER_CONTAINER --format '{{.Config.Image}}' 2>/dev/null)
echo ""
echo "New version: $NEW_VERSION"

if echo "$NEW_VERSION" | grep -q "2026-01-20-r2"; then
    echo "✅ Successfully updated to 2026-01-20-r2"
else
    echo "⚠️  Version check inconclusive"
fi

# Step 9: Test accessibility
echo ""
echo "Step 9: Testing accessibility..."
sleep 5
HTTP_167=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5 http://192.168.11.167:80 2>&1 || echo "000")
if [ "$HTTP_167" = "200" ] || [ "$HTTP_167" = "301" ] || [ "$HTTP_167" = "302" ] || [ "$HTTP_167" = "308" ]; then
    echo "✅ NPMplus is accessible (HTTP ${HTTP_167})"
else
    echo "⚠️  NPMplus returned HTTP ${HTTP_167} (may need more time to start)"
fi

echo ""
echo "=========================================="
echo "Update Complete!"
echo "=========================================="
echo ""
echo "Test NPMplus:"
echo "  curl -I http://192.168.11.167:80"
echo "  curl -I https://192.168.11.167:81 -k"
echo ""
