#!/bin/bash

# Flutter Tank Web App - Deployment Script
# This script builds and deploys the web app in a Docker container on port 8888

set -e

# Configuration
IMAGE_NAME="flutter-tank-web"
CONTAINER_NAME="flutter-tank-web-container"
PORT=8888

echo "🚀 Starting deployment of Flutter Tank Web App..."
echo "================================================"

# Stop and remove existing container if running
if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then
    echo "⏹️  Stopping existing container..."
    docker stop $CONTAINER_NAME
fi

if [ "$(docker ps -aq -f name=$CONTAINER_NAME)" ]; then
    echo "🗑️  Removing existing container..."
    docker rm $CONTAINER_NAME
fi

# Remove old image (optional - comment out to keep old images)
if [ "$(docker images -q $IMAGE_NAME)" ]; then
    echo "🗑️  Removing old image..."
    docker rmi $IMAGE_NAME || true
fi

# Build new Docker image (from parent directory to include web files)
echo "🔨 Building Docker image..."
cd ..
docker build -f installDocker/Dockerfile -t $IMAGE_NAME .
cd installDocker

# Run container
echo "🚀 Starting container on port $PORT..."
docker run -d \
    --name $CONTAINER_NAME \
    -p $PORT:80 \
    --restart unless-stopped \
    $IMAGE_NAME

# Wait a moment for container to start
sleep 2

# Check if container is running
if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then
    echo ""
    echo "✅ Deployment successful!"
    echo "================================================"
    echo "🌐 Application is running at: http://localhost:$PORT"
    echo "🏥 Health check: http://localhost:$PORT/health"
    echo ""
    echo "Useful commands:"
    echo "  View logs: docker logs $CONTAINER_NAME"
    echo "  Follow logs: docker logs -f $CONTAINER_NAME"
    echo "  Stop: docker stop $CONTAINER_NAME"
    echo "  Restart: docker restart $CONTAINER_NAME"
    echo "================================================"
else
    echo "❌ Error: Container failed to start"
    echo "Check logs with: docker logs $CONTAINER_NAME"
    exit 1
fi
