#!/usr/bin/env bash
# scraper コンテナのエントリーポイント
set -euo pipefail

LOG_DIR="/app/python/_scraper/logs"
mkdir -p "$LOG_DIR"
chown -R scraper:scraper "$LOG_DIR" 2>/dev/null || true

mkdir -p /var/run/supervisor /var/log/supervisor
chmod 0755 /var/run/supervisor

# VNC パスワード設定
if [ -n "${SCRAPER_VNC_PASSWORD:-}" ]; then
    echo "[entrypoint] VNC パスワードを設定します"
    /usr/bin/x11vnc -storepasswd "$SCRAPER_VNC_PASSWORD" /etc/x11vnc.pass
    chmod 0600 /etc/x11vnc.pass
fi

# 各スクリプトディレクトリの requirements.txt をバックグラウンドで上乗せインストール。
# supervisord を先に起動して noVNC を即時利用可能にするため、同期を待たない。
# 進捗/結果は $LOG_DIR/pip-install.log を参照。
install_individual_requirements() {
    local started_at finished_at
    started_at=$(date -Iseconds)
    echo "[pip-install] started at $started_at" >> "$LOG_DIR/pip-install.log"
    shopt -s nullglob
    for req in /app/python/*/requirements.txt; do
        echo "[pip-install] installing from $req" >> "$LOG_DIR/pip-install.log"
        if ! pip install --no-cache-dir -r "$req" >> "$LOG_DIR/pip-install.log" 2>&1; then
            echo "[pip-install] WARN: $req のインストールに失敗（他を続行）" >> "$LOG_DIR/pip-install.log"
        fi
    done
    shopt -u nullglob
    finished_at=$(date -Iseconds)
    echo "[pip-install] finished at $finished_at" >> "$LOG_DIR/pip-install.log"
}

echo "[entrypoint] 個別 requirements.txt のインストールをバックグラウンドで開始します（進捗は python/_scraper/logs/pip-install.log）"
install_individual_requirements &

echo "[entrypoint] supervisord を開始します"
exec /usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf
