#!/bin/bash

# Deployment script for LittleShop to SLAB-01
# Usage: ./deploy.sh

set -e

echo "🚀 Starting LittleShop deployment to SLAB-01..."

# Configuration
REMOTE_HOST="10.0.0.11"
REMOTE_USER="sysadmin"
REMOTE_DIR="/home/sysadmin/littleshop"
PROJECT_NAME="littleshop"

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

echo -e "${YELLOW}📦 Creating deployment package...${NC}"

# Create a temporary directory for deployment files
TEMP_DIR=$(mktemp -d)
trap "rm -rf $TEMP_DIR" EXIT

# Copy necessary files
cp -r LittleShop/* $TEMP_DIR/
cp docker-compose.yml $TEMP_DIR/
cp .env.production $TEMP_DIR/.env 2>/dev/null || true

echo -e "${YELLOW}📤 Transferring files to SLAB-01...${NC}"

# Create remote directory if it doesn't exist
ssh ${REMOTE_USER}@${REMOTE_HOST} "mkdir -p ${REMOTE_DIR}"

# Transfer files using rsync
rsync -avz --progress \
    --exclude 'bin/' \
    --exclude 'obj/' \
    --exclude '*.db' \
    --exclude 'logs/' \
    $TEMP_DIR/ ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}/

echo -e "${YELLOW}🔨 Building Docker image on SLAB-01...${NC}"

# Build the Docker image on the remote server
ssh ${REMOTE_USER}@${REMOTE_HOST} << 'ENDSSH'
cd /home/sysadmin/littleshop
echo "Building Docker image..."
docker compose build --no-cache

echo "Stopping existing container if running..."
docker compose down 2>/dev/null || true

echo "Starting LittleShop container..."
docker compose up -d

echo "Waiting for container to be healthy..."
sleep 10

echo "Container status:"
docker compose ps

echo "Container logs (last 20 lines):"
docker compose logs --tail=20
ENDSSH

echo -e "${GREEN}✅ Deployment complete!${NC}"
echo -e "${GREEN}LittleShop should be accessible at: http://${REMOTE_HOST}:5000${NC}"
echo ""
echo "Useful commands:"
echo "  - View logs: ssh ${REMOTE_USER}@${REMOTE_HOST} 'cd ${REMOTE_DIR} && docker compose logs -f'"
echo "  - Restart: ssh ${REMOTE_USER}@${REMOTE_HOST} 'cd ${REMOTE_DIR} && docker compose restart'"
echo "  - Stop: ssh ${REMOTE_USER}@${REMOTE_HOST} 'cd ${REMOTE_DIR} && docker compose down'"