#!/usr/bin/env python
"""Use Litestream's supervisor for the server and the ordinary CLI otherwise."""

import os
import shlex
import sys
from pathlib import Path

from landing.cli import app, database

Path("/storage/workspace").mkdir(parents=True, exist_ok=True)
os.chdir("/storage/workspace")
command = ["landing", *sys.argv[1:]]


def start_server(args):
    if not os.getenv("LITESTREAM_REPLICA_URL") and not os.getenv("LITESTREAM_CONFIG"):
        sys.exit("Set LITESTREAM_REPLICA_URL or mount a config and set LITESTREAM_CONFIG before serving.")

    os.environ["LANDING_DB"] = str(database(args).resolve())
    os.execvp("litestream", ["litestream", "replicate", "-restore-if-db-not-exists", "-exec", shlex.join(command)])


app(args=sys.argv[1:], prog_name="landing", obj={"start_server": start_server})
