#!/usr/bin/env python3

import shutil
import subprocess
import sys
from pathlib import Path


PACKAGES = [
    "docker-ce",
    "docker-ce-cli",
    "containerd.io",
    "docker-buildx-plugin",
    "docker-compose-plugin",
]

CONFLICTS = [
    "docker.io",
    "docker-compose",
    "docker-doc",
    "docker-buildx",
    "podman-docker",
    "containerd",
    "runc",
]


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


def release_data():
    result = {}

    for line in Path("/etc/os-release").read_text().splitlines():
        if "=" in line:
            key, value = line.split("=", 1)
            result[key] = value.strip().strip('"')

    return result


def main():
    if shutil.which("docker"):
        run(["docker", "--version"])
        print("Docker is already installed.")
        return 0

    release = release_data()

    if release.get("ID") != "debian":
        print("Only Debian is supported.", file=sys.stderr)
        return 1

    usr_options = subprocess.check_output(
        ["findmnt", "-T", "/usr", "-no", "OPTIONS"],
        text=True,
    ).strip().split(",")

    if "ro" in usr_options:
        print("/usr is mounted read-only.", file=sys.stderr)
        return 1

    architecture = subprocess.check_output(
        ["dpkg", "--print-architecture"],
        text=True,
    ).strip()

    codename = release.get("VERSION_CODENAME", "")
    suite = "bookworm" if codename == "trixie" else codename

    selected = subprocess.run(
        ["dpkg", "--get-selections", *CONFLICTS],
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.DEVNULL,
        check=False,
    ).stdout

    conflicts = [
        fields[0]
        for line in selected.splitlines()
        if len(fields := line.split()) > 1
        and fields[1] in {"install", "hold"}
    ]

    if conflicts:
        run(["sudo", "apt-get", "remove", "-y", *conflicts])

    run(["sudo", "apt-get", "update"])
    run([
        "sudo",
        "apt-get",
        "install",
        "-y",
        "ca-certificates",
        "curl",
    ])
    run([
        "sudo",
        "install",
        "-m",
        "0755",
        "-d",
        "/etc/apt/keyrings",
    ])
    run([
        "sudo",
        "curl",
        "-fsSL",
        "https://download.docker.com/linux/debian/gpg",
        "-o",
        "/etc/apt/keyrings/docker.asc",
    ])
    run([
        "sudo",
        "chmod",
        "a+r",
        "/etc/apt/keyrings/docker.asc",
    ])

    source = (
        "Types: deb\n"
        "URIs: https://download.docker.com/linux/debian\n"
        f"Suites: {suite}\n"
        "Components: stable\n"
        f"Architectures: {architecture}\n"
        "Signed-By: /etc/apt/keyrings/docker.asc\n"
    )

    subprocess.run(
        ["sudo", "tee", "/etc/apt/sources.list.d/docker.sources"],
        input=source,
        text=True,
        stdout=subprocess.DEVNULL,
        check=True,
    )

    run(["sudo", "apt-get", "update"])
    run(["sudo", "apt-get", "install", "-y", *PACKAGES])
    run(["sudo", "systemctl", "is-active", "docker"])
    run(["sudo", "docker", "version"])
    run(["sudo", "docker", "buildx", "version"])
    run(["sudo", "docker", "compose", "version"])
    run(["sudo", "docker", "run", "--rm", "hello-world"])

    print("Docker CE is installed and verified.")
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except (OSError, subprocess.CalledProcessError) as error:
        print(f"Docker installation failed: {error}", file=sys.stderr)
        sys.exit(1)