
#!/usr/bin/env python3
import os
import sys
import tempfile
import zipfile
import shutil
import subprocess
import urllib.request

ENV = "production"
ZIP_URL = "https://beta.proxy.scanfort.com/static/dist/dist_0-9-0.zip"

def log(msg):
    print("[*]", msg)

def download(url, dest):
    log(f"Downloading archive from {url}")
    urllib.request.urlretrieve(url, dest)

def main():
    log(f"Environment: {ENV}")

    base_tmp = os.path.join(tempfile.gettempdir(), ENV, "dist")
    os.makedirs(base_tmp, exist_ok=True)

    tmp_dir = tempfile.mkdtemp(dir=base_tmp)
    zip_file = os.path.join(tmp_dir, "dist.zip")

    try:
        download(ZIP_URL, zip_file)

        log("Extracting archive")
        with zipfile.ZipFile(zip_file, "r") as z:
            z.extractall(tmp_dir)

        dist_dir = os.path.join(tmp_dir, "dist")
        bootstrap = os.path.join(dist_dir, "bootstrap.pyc")

        if not os.path.isfile(bootstrap):
            print("[!] bootstrap.pyc not found")
            sys.exit(1)

        log("Running application")
        env = os.environ.copy()
        env["ENV"] = ENV

        subprocess.run(
            [sys.executable, bootstrap],
            cwd=dist_dir,
            env=env,
            check=True,
        )

        log("Done")

    finally:
        shutil.rmtree(tmp_dir, ignore_errors=True)

if __name__ == "__main__":
    main()
