#!/bin/bash

# LittleShop Deployment Script for Hostinger VPS with Password Support
# Usage: ./deploy-with-password.sh

set -e  # Exit on any error

# Configuration
HOSTINGER_HOST="31.97.57.205"
HOSTINGER_PORT="2255"
HOSTINGER_USER="sysadmin"
SSH_KEY="./Hostinger/vps_hardening_key"
REMOTE_DIR="/opt/littleshop"
SERVICE_NAME="littleshop"
PASSWORD="Phenom12#."

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Logging function
log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}

warn() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING: $1${NC}"
}

error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR: $1${NC}"
    exit 1
}

# Check if SSH key exists
if [ ! -f "$SSH_KEY" ]; then
    error "SSH key not found at $SSH_KEY"
fi

# Check if required files exist
if [ ! -f "hostinger-docker-compose.yml" ]; then
    error "hostinger-docker-compose.yml not found"
fi

if [ ! -f "env.hostinger" ]; then
    warn "env.hostinger not found - you'll need to configure environment variables manually"
fi

log "Starting deployment to Hostinger VPS..."

# Test SSH connection
log "Testing SSH connection..."
ssh -i "$SSH_KEY" -p "$HOSTINGER_PORT" -o ConnectTimeout=10 "$HOSTINGER_USER@$HOSTINGER_HOST" "echo 'SSH connection successful'" || error "SSH connection failed"

# Create remote directory with sshpass for sudo
log "Creating remote directory structure..."
sshpass -p "$PASSWORD" ssh -i "$SSH_KEY" -p "$HOSTINGER_PORT" "$HOSTINGER_USER@$HOSTINGER_HOST" "echo '$PASSWORD' | sudo -S mkdir -p $REMOTE_DIR && echo '$PASSWORD' | sudo -S chown $HOSTINGER_USER:$HOSTINGER_USER $REMOTE_DIR"

# Copy files to server
log "Copying application files..."
scp -i "$SSH_KEY" -P "$HOSTINGER_PORT" -r LittleShop/ "$HOSTINGER_USER@$HOSTINGER_HOST:$REMOTE_DIR/"
scp -i "$SSH_KEY" -P "$HOSTINGER_PORT" hostinger-docker-compose.yml "$HOSTINGER_USER@$HOSTINGER_HOST:$REMOTE_DIR/docker-compose.yml"
scp -i "$SSH_KEY" -P "$HOSTINGER_PORT" nginx.conf "$HOSTINGER_USER@$HOSTINGER_HOST:$REMOTE_DIR/"
scp -i "$SSH_KEY" -P "$HOSTINGER_PORT" Dockerfile "$HOSTINGER_USER@$HOSTINGER_HOST:$REMOTE_DIR/"

# Copy environment file if it exists
if [ -f "env.hostinger" ]; then
    log "Copying environment configuration..."
    scp -i "$SSH_KEY" -P "$HOSTINGER_PORT" env.hostinger "$HOSTINGER_USER@$HOSTINGER_HOST:$REMOTE_DIR/.env"
fi

# Deploy on remote server
log "Building and starting containers on remote server..."
ssh -i "$SSH_KEY" -p "$HOSTINGER_PORT" "$HOSTINGER_USER@$HOSTINGER_HOST" << 'EOF'
cd /opt/littleshop

# Stop existing containers if running
if docker-compose ps 2>/dev/null | grep -q "littleshop"; then
    echo "Stopping existing containers..."
    docker-compose down
fi

# Build and start new containers
echo "Building Docker image..."
docker-compose build --no-cache

echo "Starting containers..."
docker-compose up -d

# Wait for container to be ready
echo "Waiting for application to start..."
sleep 10

# Check if container is running
if docker-compose ps | grep -q "Up"; then
    echo "✅ Deployment successful!"
    echo "Container status:"
    docker-compose ps
    echo ""
    echo "Checking application health..."

    # Try to curl the health endpoint
    if curl -f http://localhost:8081/api/test > /dev/null 2>&1; then
        echo "✅ Application is responding on port 8081"
    else
        echo "⚠️  Application may still be starting up"
    fi

    echo ""
    echo "📝 Checking recent logs:"
    docker-compose logs --tail=20 littleshop

    echo ""
    echo "📝 Next steps:"
    echo "1. Configure your domain to point to this server"
    echo "2. Set up SSL certificates if needed"
    echo "3. Configure BTCPay Server integration"
    echo "4. Test the application at https://admin.thebankofdebbie.giize.com"
else
    echo "❌ Deployment failed - containers not running"
    docker-compose logs
    exit 1
fi
EOF

if [ $? -eq 0 ]; then
    log "🎉 Deployment completed successfully!"
    log "Application should be available at:"
    log "  - http://$HOSTINGER_HOST:8081 (direct access)"
    log "  - https://admin.thebankofdebbie.giize.com (via nginx proxy)"
    log ""
    log "📋 Post-deployment checklist:"
    log "1. Verify the application is accessible"
    log "2. Check that CORS is working properly"
    log "3. Test admin login (admin/admin)"
    log "4. Monitor logs: ssh -i $SSH_KEY -p $HOSTINGER_PORT $HOSTINGER_USER@$HOSTINGER_HOST 'cd /opt/littleshop && docker-compose logs -f'"
else
    error "Deployment failed!"
fi