#!/bin/bash

# Stiftung Application - Synology NAS Deployment Script
# This script automates the deployment process

set -e  # Exit on any error

echo "🚀 Starting Stiftung Application Deployment on Synology NAS..."
echo "=================================================="

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

# Function to print colored output
print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if Docker is running
check_docker() {
    print_status "Checking Docker status..."
    if ! docker info > /dev/null 2>&1; then
        print_error "Docker is not running. Please start Docker from Package Center."
        exit 1
    fi
    print_status "Docker is running ✓"
}

# Check if docker-compose is available
check_docker_compose() {
    print_status "Checking docker-compose availability..."
    if ! command -v docker-compose &> /dev/null; then
        print_error "docker-compose not found. Installing..."
        # Try to install docker-compose if not available
        if command -v pip3 &> /dev/null; then
            pip3 install docker-compose
        else
            print_error "Please install docker-compose manually."
            exit 1
        fi
    fi
    print_status "docker-compose is available ✓"
}

# Create necessary directories
create_directories() {
    print_status "Creating necessary directories..."
    
    mkdir -p data/db
    mkdir -p data/redis
    mkdir -p data/uploads
    mkdir -p data/backups
    mkdir -p logs
    
    # Set proper permissions
    chmod 755 data/
    chmod 755 logs/
    chmod 755 data/db/
    chmod 755 data/redis/
    chmod 755 data/uploads/
    chmod 755 data/backups/
    
    print_status "Directories created ✓"
}

# Setup environment file
setup_environment() {
    print_status "Setting up environment configuration..."
    
    if [ ! -f .env ]; then
        if [ -f env.template ]; then
            cp env.template .env
            print_warning "Environment file created from template."
            print_warning "Please edit .env file with your actual values before continuing."
            print_warning "Press Enter when you're ready to continue..."
            read
        else
            print_error "env.template not found. Please create .env file manually."
            exit 1
        fi
    else
        print_status "Environment file already exists ✓"
    fi
}

# Generate secure secret key
generate_secret_key() {
    print_status "Generating secure Django secret key..."
    
    # Generate a 50-character random string
    SECRET_KEY=$(python3 -c "import secrets; print(''.join(secrets.choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)))")
    
    # Update .env file with generated secret key
    if [ -f .env ]; then
        sed -i "s/your_very_long_random_secret_key_here/$SECRET_KEY/" .env
        print_status "Secret key generated and updated in .env ✓"
    fi
}

# Build and start containers
deploy_containers() {
    print_status "Building and starting containers..."
    
    # Build the web application image
    print_status "Building web application image..."
    docker-compose build web
    
    # Start all services
    print_status "Starting all services..."
    docker-compose up -d
    
    print_status "Containers started ✓"
}

# Wait for services to be ready
wait_for_services() {
    print_status "Waiting for services to be ready..."
    
    # Wait for database
    print_status "Waiting for database..."
    timeout=60
    while [ $timeout -gt 0 ]; do
        if docker-compose exec -T db pg_isready -U stiftung_user -d stiftung > /dev/null 2>&1; then
            print_status "Database is ready ✓"
            break
        fi
        sleep 2
        timeout=$((timeout - 2))
    done
    
    if [ $timeout -le 0 ]; then
        print_error "Database failed to start within 60 seconds"
        exit 1
    fi
    
    # Wait for web service
    print_status "Waiting for web service..."
    timeout=60
    while [ $timeout -gt 0 ]; do
        if curl -f http://localhost:8081/health/ > /dev/null 2>&1; then
            print_status "Web service is ready ✓"
            break
        fi
        sleep 2
        timeout=$((timeout - 2))
    done
    
    if [ $timeout -le 0 ]; then
        print_warning "Web service may not be fully ready yet"
    fi
}

# Run database migrations
run_migrations() {
    print_status "Running database migrations..."
    
    if docker-compose exec -T web python manage.py migrate --noinput; then
        print_status "Database migrations completed ✓"
    else
        print_warning "Database migrations failed. You may need to run them manually."
    fi
}

# Create superuser if needed
create_superuser() {
    print_status "Checking if superuser exists..."
    
    if ! docker-compose exec -T web python manage.py shell -c "from django.contrib.auth.models import User; print('Superuser exists' if User.objects.filter(is_superuser=True).exists() else 'No superuser')" 2>/dev/null | grep -q "Superuser exists"; then
        print_warning "No superuser found. You can create one manually with:"
        print_warning "docker-compose exec web python manage.py createsuperuser"
    else
        print_status "Superuser exists ✓"
    fi
}

# Show deployment status
show_status() {
    print_status "Deployment completed! 🎉"
    echo ""
    echo "📋 Service Status:"
    docker-compose ps
    echo ""
    echo "🌐 Access your application at:"
    echo "   Main App: http://<your-synology-ip>:8081"
    echo ""
    echo "📁 Data directories:"
    echo "   Database: ./data/db"
    echo "   Uploads: ./data/uploads"
    echo "   Backups: ./data/backups"
    echo "   Logs: ./logs"
    echo ""
    echo "🔧 Useful commands:"
    echo "   View logs: docker-compose logs -f [service_name]"
    echo "   Stop: docker-compose down"
    echo "   Restart: docker-compose restart"
    echo "   Update: docker-compose pull && docker-compose up -d"
}

# Main deployment flow
main() {
    check_docker
    check_docker_compose
    create_directories
    setup_environment
    generate_secret_key
    deploy_containers
    wait_for_services
    run_migrations
    create_superuser
    show_status
}

# Run main function
main "$@"
