#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Metabobank deployment package builder / publisher (v4)
------------------------------------------------------
Artifact names and image tags are aligned with the client start.sh v4.1:

    metabospark.tar.gz       <- metabank/metabospark:v<ver>
    mongodb5_client.tar.gz   <- metabank/mongodb5_client:v<ver>   (must carry the dbs snapshot)
    omics.tar.gz             <- metabank/metabospark-omics:v<ver>
    docker-compose.yml       (client deployment file, v3.0 layout)
    start.sh                 (client one-click script, v4.1)
    SHA256SUMS.txt           (sha256sum -c compatible, verified by the client)

Usage
-----
    # 1) build the three images (replaces the old metabobank / MongoDB / omics commands)
    python3 docker_packag_release.py build spark  --version 3.1 --context /var/www/html/Metabobank_client
    python3 docker_packag_release.py build mongo5 --version 3.1 --from-container mongodb5_prepared
    python3 docker_packag_release.py build omics  --version 3.1 --context /var/www/html/Omics_r43

    # 2) generate checksums and ship the client compose / start.sh alongside
    python3 docker_packag_release.py bundle --version 3.1

    # 3) upload to the download site (the client defaults to
    #    https://www.metabobank.cn/download)
    python3 docker_packag_release.py upload --dest /var/www/html/download

    # 4) optional: bump the image tags in the GitHub compose file
    python3 docker_packag_release.py sync-github --version 3.1

Credentials come from the environment only (never hard-code them):
    MB_SSH_HOST   MB_SSH_PORT(default 22)   MB_SSH_USER   MB_SSH_PASS
    MB_SSH_KEY    (optional private key path; alternative to MB_SSH_PASS)
    MB_UPLOAD_DIR  default /var/www/html/download
    MB_GITHUB_TOKEN MB_GITHUB_OWNER(default yanlabsz)
    MB_GITHUB_REPO(default metabobank_docker) MB_GITHUB_BRANCH(default main)

Safety differences from the legacy script
    * The mongodb5 image is never stripped: nothing under dbs/ is deleted before
      commit, and the snapshot is checked for emptiness after the build
    * Upload no longer "move then delete": previous versions are archived under
      history/<timestamp>/
    * Any failed step aborts the run (all subprocess calls use check=True)
"""

from __future__ import annotations

import argparse
import datetime
import hashlib
import os
import posixpath
import re
import shlex
import shutil
import stat
import subprocess
import sys
from typing import Dict, List, Optional

# --------------------------------------------------------------------------- #
# Target specs: target -> image repository, artifact name, default Dockerfile,
# default build context
# --------------------------------------------------------------------------- #
SPEC: Dict[str, Dict[str, str]] = {
    "spark": {
        "repo": "metabank/metabospark",
        "artifact": "metabospark.tar.gz",
        "dockerfile": "Dockerfile_metabospark",
        "context": "/var/www/html/Metabobank_client",
        "dbs_path": "",
    },
    "mongo5": {
        "repo": "metabank/mongodb5_client",
        "artifact": "mongodb5_client.tar.gz",
        "dockerfile": "Dockerfile_mongodb5_client",
        "context": "/db2/mongodb5_client",
        "dbs_path": "/opt/mongodb5_client/dbs",
    },
    "omics": {
        "repo": "metabank/metabospark-omics",
        "artifact": "omics.tar.gz",
        "dockerfile": "Dockerfile_omics",
        "context": "/var/www/html/Omics_r43",
        "dbs_path": "",
    },
}

CLIENT_FILES = ("docker-compose.yml", "start.sh")


# --------------------------------------------------------------------------- #
# Small helpers
# --------------------------------------------------------------------------- #
def log(msg: str) -> None:
    ts = datetime.datetime.now().strftime("%H:%M:%S")
    print(f"[{ts}] {msg}", flush=True)


def warn(msg: str) -> None:
    print(f"[WARN] {msg}", file=sys.stderr, flush=True)


def die(msg: str, code: int = 1) -> None:
    print(f"[ERROR] {msg}", file=sys.stderr, flush=True)
    sys.exit(code)


def run(cmd: List[str], **kw) -> subprocess.CompletedProcess:
    log("$ " + " ".join(shlex.quote(c) for c in cmd))
    return subprocess.run(cmd, check=True, **kw)


def run_shell(cmd: str) -> None:
    log("$ " + cmd)
    subprocess.run(cmd, shell=True, check=True, executable="/bin/bash")


def sha256_of(path: str) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(1024 * 1024), b""):
            h.update(chunk)
    return h.hexdigest()


def human(n: int) -> str:
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if n < 1024 or unit == "TB":
            return f"{n:.1f}{unit}" if unit != "B" else f"{n}{unit}"
        n /= 1024.0
    return f"{n:.1f}TB"


def image_exists(ref: str) -> bool:
    return subprocess.run(["docker", "image", "inspect", ref],
                          stdout=subprocess.DEVNULL,
                          stderr=subprocess.DEVNULL).returncode == 0


# --------------------------------------------------------------------------- #
# Build
# --------------------------------------------------------------------------- #
def build_image(target: str, version: str, context: Optional[str],
                dockerfile: Optional[str], from_container: Optional[str],
                out_dir: str, compress_level: int) -> str:
    spec = SPEC[target]
    repo = spec["repo"]
    ref = f"{repo}:{version}"
    artifact = spec["artifact"]
    os.makedirs(out_dir, exist_ok=True)

    if from_container:
        if not image_exists(from_container) and subprocess.run(
                ["docker", "inspect", from_container],
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode != 0:
            die(f"container/image {from_container} does not exist")
        log(f"commit container {from_container} -> {ref}")
        # Commit only. Nothing under dbs/ is deleted here: the legacy script's
        # `rm -rf dbs/*` is what produced empty-database images.
        run(["docker", "commit",
             "-a", "metabobank-release",
             "-m", f"metabobank {target} {version}",
             from_container, ref])
    else:
        ctx = context or spec["context"]
        df = dockerfile or os.path.join(ctx, spec["dockerfile"])
        if not os.path.isdir(ctx):
            die(f"build context not found: {ctx} (use --context)")
        if not os.path.isfile(df):
            die(f"Dockerfile not found: {df} (use --dockerfile)")
        log(f"build {ref} from {df} (context {ctx})")
        run(["docker", "build", "-f", df, "-t", ref, ctx])

    if not image_exists(ref):
        die(f"image still missing after build: {ref}")

    # Critical check: the mongodb5 image must ship a non-empty dbs snapshot,
    # otherwise the client's first start ends up with an empty database.
    dbs = spec.get("dbs_path", "")
    if dbs:
        check = subprocess.run(["docker", "run", "--rm", "--entrypoint", "sh", ref,
                                "-c", f"ls -A {shlex.quote(dbs)} 2>/dev/null | wc -l"],
                               capture_output=True, text=True)
        cnt = check.stdout.strip() or "0"
        if check.returncode != 0 or not cnt.isdigit():
            warn(f"cannot inspect {dbs}; verify the snapshot manually")
        elif int(cnt) == 0:
            warn(f"{dbs} is empty inside {ref} - the client will start without data! "
                 f"Pack the snapshot into the image before publishing")
        else:
            log(f"dbs snapshot check passed: {cnt} entries under {dbs}")

    out_path = os.path.join(out_dir, artifact)
    tmp_path = out_path + ".part"
    log(f"docker save -> {out_path} (gzip -{compress_level}; large images take a while)")
    run_shell(f"docker save {shlex.quote(ref)} | gzip -{compress_level} > {shlex.quote(tmp_path)}")
    os.replace(tmp_path, out_path)
    size = os.path.getsize(out_path)
    log(f"done {artifact}  {human(size)}  sha256={sha256_of(out_path)[:16]}...")
    return out_path


# --------------------------------------------------------------------------- #
# Client files and checksums
# --------------------------------------------------------------------------- #
def bundle(out_dir: str, client_dir: str, version: Optional[str] = None) -> None:
    os.makedirs(out_dir, exist_ok=True)
    for name in CLIENT_FILES:
        src = os.path.join(client_dir, name)
        if not os.path.isfile(src):
            die(f"missing client file: {src}")
        dst = os.path.join(out_dir, name)
        shutil.copy2(src, dst)
        log(f"copy {name} -> {out_dir}")

    # start.sh must be executable
    sh = os.path.join(out_dir, "start.sh")
    if os.path.exists(sh):
        os.chmod(sh, os.stat(sh).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)

    # Keep the version in one place: rewrite the compose image tags on bundle
    if version:
        compose_path = os.path.join(out_dir, "docker-compose.yml")
        with open(compose_path, "r", encoding="utf-8") as fh:
            text = fh.read()
        for repo_name in ("metabank/metabospark", "metabank/mongodb5_client",
                          "metabank/metabospark-omics"):
            pattern = re.compile(rf"(image:\s*{re.escape(repo_name)}:)v[^\s]+")
            text, n = pattern.subn(rf"\g<1>v{version}", text)
            log(f"compose tag {repo_name} -> v{version} ({n} occurrence(s))")
        with open(compose_path, "w", encoding="utf-8", newline="\n") as fh:
            fh.write(text)

        # start.sh pins the same tags in IMAGE_REFS. Rewrite them as well,
        # otherwise the client would still look for the old images after a
        # version bump (images_all_present / load_images would never match).
        start_path = os.path.join(out_dir, "start.sh")
        if os.path.isfile(start_path):
            with open(start_path, "r", encoding="utf-8") as fh:
                sh_text = fh.read()
            for repo_name in ("metabank/metabospark", "metabank/mongodb5_client",
                              "metabank/metabospark-omics"):
                pattern = re.compile(rf"({re.escape(repo_name)}:)v[0-9A-Za-z._-]+")
                sh_text, n = pattern.subn(rf"\g<1>v{version}", sh_text)
                log(f"start.sh tag {repo_name} -> v{version} ({n} occurrence(s))")
            with open(start_path, "w", encoding="utf-8", newline="\n") as fh:
                fh.write(sh_text)
        else:
            warn(f"{start_path} not found; IMAGE_REFS were not updated")
    write_sums(out_dir)


def write_sums(out_dir: str) -> str:
    files = [f for f in sorted(os.listdir(out_dir))
             if f.endswith(".tar.gz") or f in CLIENT_FILES]
    if not files:
        die(f"no publishable artifacts in {out_dir}")
    path = os.path.join(out_dir, "SHA256SUMS.txt")
    lines = []
    for f in files:
        p = os.path.join(out_dir, f)
        if not os.path.isfile(p):
            continue
        lines.append(f"{sha256_of(p)}  {f}")
        log(f"sha256 {f}")
    with open(path, "w", encoding="utf-8", newline="\n") as fh:
        fh.write("\n".join(lines) + "\n")
    log(f"SHA256SUMS.txt written with {len(lines)} entries: {path}")
    return path


# --------------------------------------------------------------------------- #
# Upload (versioned archive, never delete history)
# --------------------------------------------------------------------------- #
def sftp_client():
    try:
        import paramiko  # type: ignore
    except ImportError:
        die("paramiko is required: python3 -m pip install paramiko")

    host = os.environ.get("MB_SSH_HOST")
    user = os.environ.get("MB_SSH_USER")
    if not host or not user:
        die("environment variables MB_SSH_HOST / MB_SSH_USER are required")
    port = int(os.environ.get("MB_SSH_PORT", "22"))
    key = os.environ.get("MB_SSH_KEY")
    pwd = os.environ.get("MB_SSH_PASS")

    cli = paramiko.SSHClient()
    cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    kw = {"hostname": host, "port": port, "username": user, "timeout": 20}
    if key:
        kw["key_filename"] = key
    if pwd:
        kw["password"] = pwd
    log(f"ssh {user}@{host}:{port}")
    cli.connect(**kw)
    return cli


def remote_mkdir(sftp, path: str) -> None:
    # equivalent of mkdir -p
    parts = [p for p in path.split("/") if p]
    cur = ""
    for p in parts:
        cur += "/" + p
        try:
            sftp.stat(cur)
        except IOError:
            sftp.mkdir(cur)


def upload(out_dir: str, dest: str) -> None:
    files = [f for f in sorted(os.listdir(out_dir))
             if f.endswith(".tar.gz") or f in CLIENT_FILES or f == "SHA256SUMS.txt"]
    if not files:
        die(f"nothing to upload in {out_dir}")

    stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    dest = dest.rstrip("/")
    stage = posixpath.join(dest, f".stage-{stamp}")
    history = posixpath.join(dest, "history", stamp)

    cli = sftp_client()
    sftp = cli.open_sftp()
    try:
        remote_mkdir(sftp, dest)
        remote_mkdir(sftp, stage)
        remote_mkdir(sftp, history)

        for f in files:
            local = os.path.join(out_dir, f)
            rpath = posixpath.join(stage, f)
            log(f"upload {f} ({human(os.path.getsize(local))})")
            sftp.put(local, rpath)
            if sftp.stat(rpath).st_size != os.path.getsize(local):
                die(f"size mismatch after upload: {f}")

        # Archive the previous release (move, never delete), then switch atomically
        for f in files:
            old = posixpath.join(dest, f)
            try:
                sftp.stat(old)
            except IOError:
                continue
            cli.exec_command(f"mv {shlex.quote(old)} {shlex.quote(posixpath.join(history, f))}")[1].channel.recv_exit_status()
            log(f"archived old {f} -> history/{stamp}/")

        for f in files:
            cmd = (f"mv {shlex.quote(posixpath.join(stage, f))} "
                   f"{shlex.quote(posixpath.join(dest, f))}")
            chan = cli.exec_command(cmd)[1].channel
            if chan.recv_exit_status() != 0:
                die(f"remote mv failed: {f}")
        cli.exec_command(f"rmdir {shlex.quote(stage)}")[1].channel.recv_exit_status()
        log(f"release published to {dest} (previous release kept under history/{stamp}/)")
    finally:
        sftp.close()
        cli.close()


# --------------------------------------------------------------------------- #
# Optional: sync the GitHub compose file
# --------------------------------------------------------------------------- #
def github_sync(version: str) -> None:
    token = os.environ.get("MB_GITHUB_TOKEN")
    if not token:
        warn("MB_GITHUB_TOKEN is not set, skipping GitHub sync")
        return
    import base64
    import json
    import urllib.request

    owner = os.environ.get("MB_GITHUB_OWNER", "yanlabsz")
    repo = os.environ.get("MB_GITHUB_REPO", "metabobank_docker")
    branch = os.environ.get("MB_GITHUB_BRANCH", "main")
    path = "docker-compose.yml"
    url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}"
    headers = {"Authorization": f"token {token}", "Content-Type": "application/json",
               "Accept": "application/vnd.github+json"}

    req = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(req, timeout=20) as r:
        meta = json.load(r)
    content = base64.b64decode(meta["content"]).decode("utf-8")

    for repo_name in ("metabank/metabospark", "metabank/mongodb5_client",
                      "metabank/metabospark-omics"):
        pattern = re.compile(rf"image:\s*{re.escape(repo_name)}:[^\s]+")
        content = pattern.sub(f"image: {repo_name}:v{version}", content)

    body = json.dumps({
        "message": f"chore: bump images to v{version}",
        "content": base64.b64encode(content.encode("utf-8")).decode("utf-8"),
        "sha": meta["sha"],
        "branch": branch,
    }).encode("utf-8")
    req = urllib.request.Request(url, data=body, headers=headers, method="PUT")
    with urllib.request.urlopen(req, timeout=20) as r:
        log(f"GitHub updated {owner}/{repo}:{path} -> v{version} ({r.status})")


# --------------------------------------------------------------------------- #
# CLI
# --------------------------------------------------------------------------- #
def main() -> None:
    here = os.path.dirname(os.path.abspath(__file__))
    ap = argparse.ArgumentParser(
        description="Build and publish Metabobank deployment packages (artifacts aligned with start.sh v4.1)")
    sub = ap.add_subparsers(dest="cmd", required=True)

    b = sub.add_parser("build", help="build an image and export it as tar.gz")
    b.add_argument("target", choices=["spark", "mongo5", "omics", "all"])
    b.add_argument("--version", required=True, help="image tag, e.g. 3.1")
    b.add_argument("--context", help="build context directory (defaults per target)")
    b.add_argument("--dockerfile", help="Dockerfile path (default <context>/Dockerfile_<target>)")
    b.add_argument("--from-container", help="mongo5 only: commit an already prepared container")
    b.add_argument("--out", default=os.path.join(here, "dist"))
    b.add_argument("--gzip-level", type=int, default=1,
                   help="compression level, 1 fastest .. 9 smallest (default 1)")

    s = sub.add_parser("sums", help="rebuild SHA256SUMS.txt only")
    s.add_argument("--dir", default=os.path.join(here, "dist"))

    bun = sub.add_parser("bundle", help="copy docker-compose.yml / start.sh into the output dir and write checksums")
    bun.add_argument("--dir", default=os.path.join(here, "dist"))
    bun.add_argument("--client-dir", default=here)
    bun.add_argument("--version", help="also rewrite the compose image tags to v<version>")

    up = sub.add_parser("upload", help="upload to the download site (previous release is archived)")
    up.add_argument("--dir", default=os.path.join(here, "dist"))
    up.add_argument("--dest", default=os.environ.get("MB_UPLOAD_DIR", "/var/www/html/download"))

    g = sub.add_parser("sync-github", help="bump the image tags in the GitHub compose file")
    g.add_argument("--version", required=True)

    args = ap.parse_args()

    if args.cmd == "build":
        targets = ["spark", "mongo5", "omics"] if args.target == "all" else [args.target]
        for t in targets:
            if t == "mongo5" and not args.from_container:
                warn("mongo5 without --from-container: building from a Dockerfile. "
                     "If your snapshot lives inside a container, use --from-container <name> instead")
            build_image(
                target=t,
                version=args.version,
                context=args.context,
                dockerfile=args.dockerfile,
                from_container=args.from_container if t == "mongo5" else None,
                out_dir=args.out,
                compress_level=args.gzip_level,
            )
        write_sums(args.out)

    elif args.cmd == "sums":
        write_sums(args.dir)

    elif args.cmd == "bundle":
        bundle(args.dir, args.client_dir, args.version)

    elif args.cmd == "upload":
        upload(args.dir, args.dest)

    elif args.cmd == "sync-github":
        github_sync(args.version)


if __name__ == "__main__":
    main()
