set -e
BASE=/srv/flow2api
TS=$(date +%Y%m%d_%H%M%S)
USER_NAME=$(id -un)

sudo mkdir -p "$BASE" "$BASE/.trash" "$BASE/config" "$BASE/data" "$BASE/tmp"
sudo chown -R "$USER_NAME":"$USER_NAME" "$BASE"

if [ -d "$BASE/repo" ]; then
  mv "$BASE/repo" "$BASE/.trash/repo_$TS"
fi
mkdir -p "$BASE/repo"
tar -xzf /tmp/flow2api_3a12d7b.tar.gz -C "$BASE/repo"

python3 <<'INNERPY'
from pathlib import Path
import secrets

base = Path('/srv/flow2api')
admin_password = secrets.token_hex(12)
api_key = 'flow2api_' + secrets.token_hex(16)
config_text = """[global]
api_key = \"{api_key}\"
admin_username = \"admin\"
admin_password = \"{admin_password}\"

[flow]
labs_base_url = \"https://labs.google/fx/api\"
api_base_url = \"https://aisandbox-pa.googleapis.com/v1\"
timeout = 120
max_retries = 4
image_request_timeout = 40
image_timeout_retry_count = 1
image_timeout_retry_delay = 0.8
image_timeout_use_media_proxy_fallback = true
image_prefer_media_proxy = true
image_slot_wait_timeout = 900
image_launch_soft_limit = 25
image_launch_wait_timeout = 900
image_launch_stagger_ms = 250
video_slot_wait_timeout = 480
video_launch_soft_limit = 20
video_launch_wait_timeout = 480
video_launch_stagger_ms = 250
poll_interval = 3.0
max_poll_attempts = 200

[server]
host = \"0.0.0.0\"
port = 8000

[debug]
enabled = false
log_requests = true
log_responses = true
mask_token = true

[proxy]
proxy_enabled = false
proxy_url = \"\"

[generation]
image_timeout = 300
video_timeout = 1500

[call_logic]
call_mode = \"default\"

[admin]
error_ban_threshold = 3

[cache]
enabled = false
timeout = 7200
base_url = \"https://flow2api.tap365.org\"

[captcha]
captcha_method = \"yescaptcha\"
browser_recaptcha_settle_seconds = 1.0
browser_launch_background = true
personal_max_resident_tabs = 5
personal_idle_tab_ttl_seconds = 600
yescaptcha_api_key = \"\"
yescaptcha_base_url = \"https://api.yescaptcha.com\"
remote_browser_base_url = \"\"
remote_browser_api_key = \"\"
remote_browser_timeout = 35
""".format(api_key=api_key, admin_password=admin_password)
(base / 'config' / 'setting.toml').write_text(config_text)
compose_text = """services:
  flow2api:
    build:
      context: ./repo
      dockerfile: Dockerfile
    image: flow2api:prod-3a12d7b
    container_name: flow2api
    restart: unless-stopped
    ports:
      - \"127.0.0.1:38000:8000\"
    volumes:
      - ./data:/app/data
      - ./tmp:/app/tmp
      - ./config/setting.toml:/app/config/setting.toml:ro
    environment:
      PYTHONUNBUFFERED: \"1\"
"""
(base / 'docker-compose.yml').write_text(compose_text)
print(f'ADMIN_USERNAME=admin')
print(f'ADMIN_PASSWORD={admin_password}')
print(f'API_KEY={api_key}')
INNERPY

cd "$BASE"
docker compose -f docker-compose.yml up -d --build
