#!/usr/bin/env python3

import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path


COMPOSE_FILE = Path.cwd() / "compose.silo.yaml"

COMPOSE = """\
services:
  silo:
    image: docker.io/pgsty/silo:latest
    container_name: silo
    restart: unless-stopped
    command: server /data --console-address ":9001"
    environment:
      MINIO_ROOT_USER: admin
      MINIO_ROOT_PASSWORD: adminadmin
    ports:
      - "9000:9000"
      - "9001:9001"
    volumes:
      - silo-data:/data

volumes:
  silo-data:
"""


def run(command):
    subprocess.run(command, check=True)


def wait_until_ready(timeout=60):
    deadline = time.monotonic() + timeout
    health_url = "http://127.0.0.1:9000/minio/health/live"

    while time.monotonic() < deadline:
        try:
            with urllib.request.urlopen(
                health_url,
                timeout=2,
            ) as response:
                if response.status == 200:
                    return True
        except (urllib.error.URLError, TimeoutError):
            pass

        time.sleep(2)

    return False


def main():
    if not shutil.which("docker"):
        print("Docker is not installed.", file=sys.stderr)
        return 1

    run(["docker", "compose", "version"])

    COMPOSE_FILE.write_text(COMPOSE, encoding="utf-8")

    run([
        "docker",
        "compose",
        "-f",
        str(COMPOSE_FILE),
        "up",
        "-d",
    ])

    if not wait_until_ready():
        print(
            "Silo did not become ready within 60 seconds.",
            file=sys.stderr,
        )
        return 1

    print("Silo is ready.")
    print("Console:  http://127.0.0.1:9001")
    print("S3 API:   http://127.0.0.1:9000")
    print("Login:    admin")
    print("Password: adminadmin")
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except (OSError, subprocess.CalledProcessError) as error:
        print(f"Failed to start Silo: {error}", file=sys.stderr)
        sys.exit(1)