#!/bin/sh
set -e
APP_DIR=/var/www/html
echo "──────────────────────────────────────────"
echo " KOL Manager – Container Start"
echo "──────────────────────────────────────────"
cd "$APP_DIR"
# ── 1. Bootstrap .env ───────────────────────
if [ ! -f .env ]; then
if [ -f .env.docker ]; then
cp .env.docker .env
echo "[env] Copied .env.docker → .env"
else
echo "[env] WARNING: No .env or .env.docker found!"
fi
fi
# ── 2. Generate APP_KEY if empty ────────────
if ! grep -qE '^APP_KEY=base64:' .env 2>/dev/null; then
echo "[key] Generating application key directly…"
# 2a. Clear cached configs that might cause MissingAppKeyException
php artisan config:clear --quiet 2>/dev/null || true
# 2b. Generate native base64 key
NEW_KEY="base64:$(php -r 'echo base64_encode(random_bytes(32));')"
if grep -q '^APP_KEY=' .env 2>/dev/null; then
# Replace existing empty/invalid APP_KEY safely
sed -i "s|^APP_KEY=.*|APP_KEY=$NEW_KEY|" .env
else
# Append nicely
echo "APP_KEY=$NEW_KEY" >> .env
fi
fi
# 2c. Force Laravel to read from .env by ditching Docker's empty OS injection
unset APP_KEY
# ── 3. Ensure SQLite database file exists ───
if [ ! -f database/database.sqlite ]; then
echo "[db] Creating SQLite database file…"
touch database/database.sqlite
fi
# ── 4. Fix ownership / permissions ──────────
chown -R www-data:www-data \
storage \
bootstrap/cache \
database
chmod -R 775 \
storage \
bootstrap/cache \
database
# ── 5. Discover packages (composer --no-scripts skips this) ──
echo "[packages] Discovering service providers…"
php artisan package:discover --ansi 2>/dev/null || true
# ── 6. Run migrations ─────────────────────────
echo "[migrate] Running database migrations…"
php artisan migrate --force --no-interaction
# ── 7. Create public storage symlink ──────────
echo "[storage] Creating public storage symlink…"
php artisan storage:link --quiet 2>/dev/null || true
# ── 8. Cache config / routes / views ─────────
echo "[optimize] Caching configuration…"
php artisan config:cache --quiet
php artisan route:cache --quiet
php artisan view:cache --quiet
echo "──────────────────────────────────────────"
echo " All checks passed. Starting services…"
echo "──────────────────────────────────────────"
# ── 9. Hand off to Supervisor ────────────────
exec supervisord -c /etc/supervisord.conf