#!/bin/bash

# Deployment script for MerchBay Admin
# This can be used for manual deployments or called from CI/CD

set -e

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

# Configuration
DEPLOY_DIR="${DEPLOY_DIR:-/var/www/merchbay_admin}"
APP_NAME="merchbay_admin"
BACKUP_DIR="${DEPLOY_DIR}/backups"

echo -e "${GREEN}Starting deployment of ${APP_NAME}...${NC}"

# Create backup directory
mkdir -p "${BACKUP_DIR}"

# Backup current state
if [ -d "${DEPLOY_DIR}/storage" ]; then
    echo -e "${YELLOW}Creating backup...${NC}"
    BACKUP_FILE="${BACKUP_DIR}/backup_$(date +%Y%m%d_%H%M%S).tar.gz"
    tar -czf "${BACKUP_FILE}" -C "${DEPLOY_DIR}" storage .env 2>/dev/null || true
    echo -e "${GREEN}Backup created: ${BACKUP_FILE}${NC}"
fi

# Navigate to deployment directory
cd "${DEPLOY_DIR}"

# Check if .env exists
if [ ! -f .env ]; then
    echo -e "${RED}Error: .env file not found!${NC}"
    echo "Please create .env file with database credentials"
    exit 1
fi

# Pull latest code (if using git deployment)
if [ -d .git ]; then
    echo -e "${YELLOW}Pulling latest code...${NC}"
    git pull origin main || git pull origin master
fi

# Stop existing containers
echo -e "${YELLOW}Stopping existing containers...${NC}"
docker compose down

# Build new image
echo -e "${YELLOW}Building Docker image...${NC}"
docker compose build --no-cache

# Start containers
echo -e "${YELLOW}Starting containers...${NC}"
docker compose up -d

# Wait for container to be ready
echo -e "${YELLOW}Waiting for application to start...${NC}"
sleep 10

# Run migrations
echo -e "${YELLOW}Running database migrations...${NC}"
docker compose exec -T app php artisan migrate --force || {
    echo -e "${RED}Migration failed! Rolling back...${NC}"
    docker compose down
    exit 1
}

# Clear and cache configuration
echo -e "${YELLOW}Optimizing application...${NC}"
docker compose exec -T app php artisan config:cache
docker compose exec -T app php artisan route:cache
docker compose exec -T app php artisan view:cache

# Set proper permissions
echo -e "${YELLOW}Setting permissions...${NC}"
docker compose exec -T app chown -R www-data:www-data /var/www/html/storage
docker compose exec -T app chmod -R 755 /var/www/html/storage

# Health check
echo -e "${YELLOW}Performing health check...${NC}"
sleep 5
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8080)

if [ "$HTTP_STATUS" -eq 200 ]; then
    echo -e "${GREEN}✓ Deployment successful! Application is running.${NC}"
    echo -e "${GREEN}✓ HTTP Status: ${HTTP_STATUS}${NC}"
    
    # Keep only last 5 backups
    cd "${BACKUP_DIR}"
    ls -t backup_*.tar.gz 2>/dev/null | tail -n +6 | xargs -r rm
    
    echo -e "${GREEN}Deployment completed successfully!${NC}"
else
    echo -e "${RED}✗ Health check failed! HTTP Status: ${HTTP_STATUS}${NC}"
    echo -e "${YELLOW}Check logs: docker compose logs app${NC}"
    exit 1
fi

# Display container status
echo -e "${YELLOW}Container status:${NC}"
docker compose ps
