#!/bin/bash
set -e

cd /var/www/html

# --- SSL 証明書の準備 ---
mkdir -p /etc/nginx/ssl
if [ ! -f /etc/nginx/ssl/server.crt ]; then
    echo "[entrypoint] 自己署名SSL証明書を生成します..."
    openssl req -x509 -nodes -days 3650 \
        -newkey rsa:2048 \
        -keyout /etc/nginx/ssl/server.key \
        -out /etc/nginx/ssl/server.crt \
        -subj "/C=JP/ST=Tokyo/L=Tokyo/O=match_12/CN=${APP_DOMAIN:-localhost}"
fi

# --- 初回起動時の初期化 ---

# storage サブディレクトリを作成（ボリュームマウントで空になる場合に対応）
mkdir -p storage/app/public \
         storage/framework/cache/data \
         storage/framework/sessions \
         storage/framework/views \
         storage/logs

# storage:link
php artisan storage:link 2>/dev/null || true

# パーミッション確保
chown -R www-data:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache

# --- /var/run/docker.sock の権限を www-data に許可 ---
# Web UI から `docker inspect` でコンテナ状態を確認するために必要。
# ホストの docker.sock の GID はホスト依存（Synology / Linux ディストリビューションで異なる）なので、
# 起動時に動的に検出して、対応するグループに www-data を追加する。
if [ -S /var/run/docker.sock ]; then
    DOCKER_SOCK_GID=$(stat -c '%g' /var/run/docker.sock 2>/dev/null || echo '')
    if [ -n "$DOCKER_SOCK_GID" ] && [ "$DOCKER_SOCK_GID" != "0" ]; then
        # GID に対応するグループ名を取得。無ければ docker_host という名前で作成。
        EXISTING_GROUP=$(getent group "$DOCKER_SOCK_GID" | cut -d: -f1 || true)
        if [ -z "$EXISTING_GROUP" ]; then
            groupadd -g "$DOCKER_SOCK_GID" docker_host 2>/dev/null || true
            EXISTING_GROUP=docker_host
        fi
        if [ -n "$EXISTING_GROUP" ]; then
            usermod -aG "$EXISTING_GROUP" www-data 2>/dev/null || true
            echo "[entrypoint] docker.sock GID=$DOCKER_SOCK_GID に対応するグループ '$EXISTING_GROUP' に www-data を追加しました"
        fi
    elif [ "$DOCKER_SOCK_GID" = "0" ]; then
        # GID=0 (root所有) の場合は usermod で root グループに追加（Synology はこのケースが多い）
        usermod -aG root www-data 2>/dev/null || true
        echo "[entrypoint] docker.sock は GID=0 (root) のため www-data を root グループに追加しました"
    fi
fi

# --- Composer install ---
echo "[entrypoint] composer install を実行します..."
composer install --no-interaction --optimize-autoloader

# --- MySQL 接続待ち ---
echo "[entrypoint] MySQL の起動を待機しています..."
max_retries=30
count=0
until php artisan db:monitor --databases=mysql 2>/dev/null || php -r "new PDO('mysql:host=${DB_HOST:-mysql};port=${DB_PORT:-3306};dbname=${DB_DATABASE:-match_12}', '${DB_USERNAME:-match_12}', '${DB_PASSWORD:-secret}');" 2>/dev/null; do
    count=$((count + 1))
    if [ $count -ge $max_retries ]; then
        echo "[entrypoint] MySQL への接続がタイムアウトしました"
        break
    fi
    echo "[entrypoint] MySQL 待機中... ($count/$max_retries)"
    sleep 2
done

# --- Redis 接続待ち ---
echo "[entrypoint] Redis の起動を待機しています..."
max_retries=30
count=0
until php -r "\$r = new Redis(); \$r->connect('${REDIS_HOST:-redis}', (int)(getenv('REDIS_PORT') ?: 6379), 1); if (getenv('REDIS_PASSWORD') && getenv('REDIS_PASSWORD') !== 'null') \$r->auth(getenv('REDIS_PASSWORD')); exit(\$r->ping() ? 0 : 1);" 2>/dev/null; do
    count=$((count + 1))
    if [ $count -ge $max_retries ]; then
        echo "[entrypoint] Redis への接続がタイムアウトしました（キュー/キャッシュが利用不可になる可能性があります）"
        break
    fi
    echo "[entrypoint] Redis 待機中... ($count/$max_retries)"
    sleep 2
done

# --- マイグレーション実行 ---
echo "[entrypoint] php artisan migrate を実行します..."
php artisan migrate --force --no-interaction

# --- フロントエンドビルド ---
echo "[entrypoint] npm install を実行します..."
npm ci --no-audit --no-fund
echo "[entrypoint] npm run build を実行します..."
npm run build

# --- キャッシュ最適化 ---
echo "[entrypoint] キャッシュを最適化します..."
php artisan config:cache
php artisan route:cache
php artisan view:cache

# --- パーミッション再確保（config:cache 等が root でファイル生成するため） ---
chown -R www-data:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache

# --- Supervisor ログディレクトリ ---
mkdir -p /var/log/supervisor

echo "[entrypoint] 起動完了 – Supervisor を開始します"
exec "$@"
