#!/bin/bash

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

# Function to display help menu
show_help() {
    echo -e "${GREEN}BYOM Project Management Script${NC}"
    echo -e "\nUsage: ./init-byom.sh [command] [args]"
    echo -e "\nCommands:"
    echo "  init [host]  Initialize environment files (optional: specify host, default: localhost)"
    echo "  deploy       Deploy to production"
    echo "  clean        Clean up Docker resources"
    echo -e "\nExamples:"
    echo "  ./init-byom.sh init"
    echo "  ./init-byom.sh up"
}

# Function to initialize environment files
init_env() {
    echo -e "${GREEN}Initializing environment files for BYOM project...${NC}\n"

    # Create .env for root directory (docker-compose)
    cat > .env << EOL
# Docker Compose Environment Variables
DOMAIN=${DOMAIN}
NODE_ENV=production
EOL
    echo -e "${GREEN}✓${NC} Created root .env file"

    # Create .env for byom-web
    mkdir -p byom-web
    cat > byom-web/.env << EOL
# Next.js Environment Variables
NEXT_PUBLIC_API_CORE_URL=https://${DOMAIN}/api/v1/core
EOL
    echo -e "${GREEN}✓${NC} Created byom-web/.env file"

    # Create data directory and initialize app.db for byom-core
    mkdir -p byom-core/data
    touch byom-core/data/app.db
    echo -e "${GREEN}✓${NC} Created byom-core/data/app.db file"
}

# Function to deploy to production
deploy_production() {
    echo -e "${GREEN}Deploying to production...${NC}"
    
    # Pull latest changes
    git pull origin main
    
    # Build fresh images
    docker-compose -f docker-compose.yml build
    
    # Deploy with production configuration
    docker-compose -f docker-compose.yml up -d
    
    echo -e "${GREEN}Deployment completed!${NC}"
}

# Function to clean up Docker resources
clean_resources() {
    echo -e "${YELLOW}Cleaning up Docker resources...${NC}"
    docker-compose down -v --remove-orphans
    echo -e "${GREEN}Cleanup completed!${NC}"
}

# Main script logic
case "$1" in
    "init")
        if [ -n "$2" ]; then
            DOMAIN="$2" init_env
        else
            DOMAIN="localhost" init_env
        fi
        ;;
    "deploy")
        deploy_production
        ;;
    "clean")
        clean_resources
        ;;
    "help"|"--help"|"-h"|"")
        show_help
        ;;
    *)
        echo -e "${RED}Invalid command. Use './init-byom.sh help' to see available commands.${NC}"
        exit 1
        ;;
esac

exit 0