#!/usr/bin/env python3
#
# Author: Jason Beattie
# Blog:   Oracle Infrastructure Blogger
#         https://www.oracle-infrastructure-blogger.com/
# Guide:  Copying OCI Object Storage from Commercial Frankfurt to
#         EU Sovereign Cloud
#
# What this is
# ------------
# A small OCI CLI helper that copies Object Storage objects from one
# tenancy to another. I used it to move data from Commercial Frankfurt
# (eu-frankfurt-1) into EU Sovereign Frankfurt (eu-frankfurt-2) from a
# transfer host (my Mac). There is no native cross-realm copy for this,
# so each object is downloaded, uploaded under the same name, checksum
# checked, then the staging file is cleared.
#
# Setup (once)
#   1. Install the OCI CLI and create named profiles for both tenancies.
#   2. Edit SOURCE, TARGET, BUCKET_PAIRS, and STAGING_DIR below.
#   3. Replace the namespace placeholders with your real namespaces.
#   4. Make sure staging has room for the largest single object.
#
# Commands
#   python3 oci-bucket-transfer.py check
#   python3 oci-bucket-transfer.py size
#   python3 oci-bucket-transfer.py copy app-data
#   python3 oci-bucket-transfer.py copy
#
# Copy rules in plain English
#   - Missing objects get copied.
#   - Same name and size on both sides are skipped.
#   - Same name but different size stops the run so you can choose.
#   - Objects that only exist on the target are left alone.
#   - Bucket settings, versions, and object metadata are not copied.
#
# Download this file from the article, or save it as
# oci-bucket-transfer.py on your transfer host.
#
"""Copy Object Storage objects between two OCI tenancies with the OCI CLI.

Author: Jason Beattie (Oracle Infrastructure Blogger).

Edit SOURCE, TARGET, BUCKET_PAIRS, and STAGING_DIR below, then run
check, size, or copy.
"""

import argparse
import json
import shutil
import subprocess
import tempfile
from pathlib import Path


# =====================================================================
# EDIT THIS SECTION
# =====================================================================

# Format: ("OCI_CLI_PROFILE", "OCI_REGION", "OBJECT_STORAGE_NAMESPACE")
SOURCE = ("COMMERCIAL", "eu-frankfurt-1", "<source-namespace>")
TARGET = ("EU_SOV", "eu-frankfurt-2", "<target-namespace>")

# Format: ("SOURCE_BUCKET", "TARGET_BUCKET")
# If only the destination bucket name differs, change the SECOND value.
BUCKET_PAIRS = (
    ("database-dumps", "database-dumps"),
    ("app-data", "app-data-sovereign"),
)

# Set this to an existing directory with room for the largest object.
# Example: STAGING_DIR = Path("/Volumes/TransferDisk")
STAGING_DIR = Path.home()

# =====================================================================

GIB = 1024 ** 3


class TransferError(Exception):
    """An error that prevents a safe copy or verification."""


def run_oci(location, *arguments):
    profile, region, _ = location
    command = [
        "oci", *arguments,
        "--profile", profile,
        "--auth", "api_key",
        "--region", region,
    ]
    result = subprocess.run(
        command,
        check=True,
        stdout=subprocess.PIPE,
        text=True,
    )
    return result.stdout


def object_command(location, operation, bucket, *arguments):
    _, _, namespace = location
    return run_oci(
        location, "os", "object", operation,
        "--namespace-name", namespace,
        "--bucket-name", bucket,
        *arguments,
    )


def check_namespace(location):
    profile, _, expected = location
    actual = run_oci(
        location, "os", "ns", "get",
        "--query", "data", "--raw-output",
    ).strip()
    if actual != expected:
        raise TransferError(
            f"{profile}: expected namespace {expected!r}, got {actual!r}."
        )
    print(f"OK {profile}: namespace {actual}", flush=True)


def check_access(pairs):
    check_namespace(SOURCE)
    check_namespace(TARGET)
    for source_bucket, target_bucket in pairs:
        object_command(SOURCE, "list", source_bucket, "--limit", "1")
        object_command(TARGET, "list", target_bucket, "--limit", "1")
        print(f"OK object listing: {source_bucket} -> {target_bucket}", flush=True)


def inventory(location, bucket):
    output = object_command(
        location, "list", bucket,
        "--all", "--fields", "name,size", "--output", "json",
    )

    try:
        response = json.loads(output)
    except json.JSONDecodeError as error:
        raise TransferError(f"{bucket}: OCI returned invalid listing JSON.") from error

    # On an empty listing, some OCI CLI versions omit data or return null.
    if not isinstance(response, dict) or response.keys() - {"data", "prefixes"}:
        raise TransferError(f"{bucket}: unexpected OCI listing response.")
    rows = response.get("data")
    if rows is None:
        rows = []
    if not isinstance(rows, list):
        raise TransferError(f"{bucket}: expected a list of objects.")

    objects = {}
    for row in rows:
        if not isinstance(row, dict):
            raise TransferError(f"{bucket}: invalid object entry in listing.")
        name, size = row.get("name"), row.get("size")
        if not isinstance(name, str) or type(size) is not int or size < 0:
            raise TransferError(f"{bucket}: invalid object name or byte size.")
        if name in objects:
            raise TransferError(f"{bucket}: duplicate object name {name!r}.")
        objects[name] = size
    return objects


def report_sizes(pairs):
    print(f"{'Source bucket':28} {'Objects':>10} {'Total GiB':>12} {'Largest GiB':>12}")
    total_bytes = 0
    largest_bytes = 0
    for source_bucket, _ in pairs:
        objects = inventory(SOURCE, source_bucket)
        bucket_bytes = sum(objects.values())
        largest_object = max(objects.values(), default=0)
        total_bytes += bucket_bytes
        largest_bytes = max(largest_bytes, largest_object)
        print(
            f"{source_bucket:28} {len(objects):>10,} "
            f"{bucket_bytes / GIB:>12.3f} {largest_object / GIB:>12.3f}",
            flush=True,
        )

    free_bytes = shutil.disk_usage(STAGING_DIR).free
    print(f"\nTotal source data: {total_bytes / GIB:.3f} GiB")
    print(f"Largest source object: {largest_bytes / GIB:.3f} GiB")
    print(f"Free staging space: {free_bytes / GIB:.3f} GiB ({STAGING_DIR})")


def copy_object(source_bucket, target_bucket, name, size):
    free_bytes = shutil.disk_usage(STAGING_DIR).free
    if size > free_bytes:
        raise TransferError(
            f"Insufficient staging space for {source_bucket}/{name!r}. "
            f"Need {size:,} bytes and have {free_bytes:,} bytes."
        )

    print(f"COPY {name!r} ({size:,} bytes)", flush=True)
    with tempfile.TemporaryDirectory(prefix="oci-transfer-", dir=STAGING_DIR) as directory:
        staged_file = Path(directory) / "object"
        object_command(
            SOURCE, "get", source_bucket,
            f"--name={name}", "--file", str(staged_file),
        )
        downloaded_size = staged_file.stat().st_size
        if downloaded_size != size:
            raise TransferError(
                f"Size changed for {source_bucket}/{name!r}. "
                f"Expected {size:,} bytes and downloaded {downloaded_size:,}."
            )

        output = object_command(
            TARGET, "put", target_bucket,
            f"--name={name}", "--file", str(staged_file),
            "--no-overwrite", "--verify-checksum", "--output", "json",
        )
        if output.strip():
            print(output.strip(), flush=True)
        # OCI prints its own result, including when --no-overwrite skips a
        # destination object created after the initial target listing.


def copy_bucket(source_bucket, target_bucket):
    print(f"\n=== {source_bucket} -> {target_bucket} ===", flush=True)
    source = inventory(SOURCE, source_bucket)
    target = inventory(TARGET, target_bucket)

    for name, size in source.items():
        if name in target and target[name] != size:
            raise TransferError(
                f"Size conflict for {target_bucket}/{name!r}. "
                f"Source has {size:,} bytes and target has {target[name]:,} bytes."
            )

    for name, size in sorted(source.items()):
        if name in target:
            print(f"SKIP {name!r} (same name and size)", flush=True)
            continue
        copy_object(source_bucket, target_bucket, name, size)

    final_target = inventory(TARGET, target_bucket)
    for name, size in source.items():
        if final_target.get(name) != size:
            raise TransferError(
                f"Verification failed for {target_bucket}/{name!r}. "
                f"Expected {size:,} bytes and found {final_target.get(name)!r}."
            )

    print(f"VERIFIED {len(source):,} source names and byte sizes", flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("action", choices=("check", "size", "copy"))
    parser.add_argument("buckets", nargs="*", metavar="SOURCE_BUCKET")
    args = parser.parse_args()

    if SOURCE[2].startswith("<") or TARGET[2].startswith("<"):
        parser.error("Set both namespaces in the EDIT THIS SECTION block.")

    mappings = dict(BUCKET_PAIRS)
    if not mappings or len(mappings) != len(BUCKET_PAIRS):
        parser.error("Configure BUCKET_PAIRS with one mapping per source bucket.")

    selected = args.buckets or list(mappings)
    unknown = sorted(set(selected) - mappings.keys())
    if unknown:
        parser.error(f"Unknown source bucket(s): {', '.join(unknown)}")

    pairs = [(bucket, mappings[bucket]) for bucket in dict.fromkeys(selected)]

    if args.action == "check":
        check_access(pairs)
    elif args.action == "size":
        report_sizes(pairs)
    else:
        check_access(pairs)
        for source_bucket, target_bucket in pairs:
            copy_bucket(source_bucket, target_bucket)


if __name__ == "__main__":
    try:
        main()
    except subprocess.CalledProcessError as error:
        raise SystemExit(f"OCI CLI failed with exit code {error.returncode}.") from None
    except (OSError, TransferError) as error:
        raise SystemExit(f"Transfer error: {error}") from None
