#!/bin/bash
# Script completo para criar a imagem Docker do Krayin

# ========================================
# 1. CRIAR ESTRUTURA DE PASTAS
# ========================================
mkdir -p docker

# ========================================
# 2. CRIAR docker/nginx.conf
# ========================================
cat > docker/nginx.conf << '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;
    }
}
EOF

# ========================================
# 3. CRIAR docker/supervisord.conf
# ========================================
cat > docker/supervisord.conf << '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
EOF

# ========================================
# 4. CRIAR .dockerignore
# ========================================
cat > .dockerignore << 'EOF'
.git
.gitignore
.env
node_modules
vendor
storage/logs/*
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
bootstrap/cache/*
.DS_Store
Thumbs.db
EOF

# ========================================
# 5. CRIAR Dockerfile
# ========================================
cat > Dockerfile << 'EOF'
FROM php:8.1-fpm

# Instalar dependências do sistema
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 \
    && apt-get clean && rm -rf /var/lib/apt/lists/*

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

# Criar diretório da aplicação
WORKDIR /var/www/html

# Copiar arquivos do projeto
COPY . .

# Instalar dependências do Composer
RUN composer install --no-dev --optimize-autoloader --no-interaction

# 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

# Criar script de entrada
RUN echo '#!/bin/bash\n\
php artisan config:cache\n\
php artisan route:cache\n\
php artisan view:cache\n\
exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf' > /entrypoint.sh \
    && chmod +x /entrypoint.sh

EXPOSE 80

ENTRYPOINT ["/entrypoint.sh"]
EOF

# ========================================
# 6. CONSTRUIR A IMAGEM
# ========================================
echo "Construindo a imagem Docker..."
docker build -t growup:latest .

# ========================================
# 7. SALVAR A IMAGEM (opcional)
# ========================================
echo "Salvando a imagem em arquivo tar..."
docker save growup:latest -o growup-latest.tar

echo ""
echo "========================================"
echo "IMAGEM CRIADA COM SUCESSO!"
echo "========================================"
echo ""
echo "Para usar no outro servidor:"
echo "1. Copie o arquivo growup-latest.tar para o servidor"
echo "2. Carregue a imagem: docker load -i growup-latest.tar"
echo "3. Use 'image: growup:latest' no seu docker-compose.yml"
echo ""
echo "Ou envie para um registry:"
echo "docker tag growup:latest seu-registry.com/growup:latest"
echo "docker push seu-registry.com/growup:latest"
echo ""
