#!/bin/bash
set -e

echo "🚀 Criando imagem Docker do Krayin..."

# Criar pasta docker se não existir
mkdir -p docker

# ========================================
# NGINX CONFIG
# ========================================
cat > docker/nginx.conf << 'NGINX_EOF'
server {
    listen 80;
    server_name _;
    root /var/www/html/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;
    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
NGINX_EOF

# ========================================
# SUPERVISOR CONFIG
# ========================================
cat > docker/supervisord.conf << 'SUPER_EOF'
[supervisord]
nodaemon=true
user=root

[program:php-fpm]
command=/usr/local/sbin/php-fpm
autostart=true
autorestart=true
priority=5
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0

[program:nginx]
command=/usr/sbin/nginx -g "daemon off;"
autostart=true
autorestart=true
priority=10
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
SUPER_EOF

# ========================================
# DOCKERIGNORE
# ========================================
cat > .dockerignore << 'IGNORE_EOF'
.git
.gitignore
node_modules
storage/logs/*
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
bootstrap/cache/*
.DS_Store
Thumbs.db
*.tar
*.tar.gz
IGNORE_EOF

# ========================================
# DOCKERFILE
# ========================================
cat > Dockerfile << 'DOCKER_EOF'
FROM php:8.2-fpm

# Instalar dependências
RUN apt-get update && apt-get install -y \
    git curl libpng-dev libonig-dev libxml2-dev \
    zip unzip libzip-dev nginx supervisor \
    && docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd zip calendar \
    && apt-get clean && rm -rf /var/lib/apt/lists/*

# Instalar Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

WORKDIR /var/www/html

# Copiar composer.json e composer.lock primeiro (cache layer)
COPY composer.json composer.lock ./

# Instalar dependências (isso vai rodar composer update se necessário)
RUN composer install --no-dev --no-scripts --no-interaction || \
    composer update --no-dev --no-scripts --no-interaction

# Copiar todo o código
COPY . .

# Rodar scripts do composer
RUN composer dump-autoload --optimize --no-dev

# Ajustar permissões
RUN chown -R www-data:www-data /var/www/html \
    && chmod -R 755 /var/www/html/storage \
    && chmod -R 755 /var/www/html/bootstrap/cache

# Copiar configurações
COPY docker/nginx.conf /etc/nginx/sites-available/default
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf

# Script de inicialização
RUN echo '#!/bin/bash' > /start.sh && \
    echo 'php artisan config:cache' >> /start.sh && \
    echo 'php artisan route:cache' >> /start.sh && \
    echo 'php artisan view:cache' >> /start.sh && \
    echo 'exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf' >> /start.sh && \
    chmod +x /start.sh

EXPOSE 80

CMD ["/start.sh"]
DOCKER_EOF

echo ""
echo "✅ Arquivos de configuração criados!"
echo ""

# ========================================
# BUILD
# ========================================
echo "🔨 Construindo imagem Docker..."
if docker build -t growup:latest .; then
    echo ""
    echo "✅ Imagem construída com sucesso!"
    echo ""
    
    # ========================================
    # SAVE
    # ========================================
    echo "💾 Salvando imagem em arquivo..."
    if docker save growup:latest -o growup-latest.tar; then
        echo ""
        echo "================================================"
        echo "✅ SUCESSO TOTAL!"
        echo "================================================"
        echo ""
        echo "📦 Arquivo criado: growup-latest.tar"
        echo "📊 Tamanho: $(du -h growup-latest.tar | cut -f1)"
        echo ""
        echo "🚀 PRÓXIMOS PASSOS:"
        echo ""
        echo "1️⃣  Transferir para o servidor:"
        echo "   scp growup-latest.tar usuario@servidor:/caminho/"
        echo ""
        echo "2️⃣  No servidor, carregar a imagem:"
        echo "   docker load -i growup-latest.tar"
        echo ""
        echo "3️⃣  No docker-compose.yml, use:"
        echo "   image: growup:latest"
        echo ""
        echo "================================================"
    else
        echo "❌ Erro ao salvar a imagem"
        exit 1
    fi
else
    echo ""
    echo "❌ Erro ao construir a imagem"
    echo ""
    echo "💡 DICA: Verifique se você está na pasta raiz do projeto Krayin"
    exit 1
fi
