#!/usr/bin/env python3

from pathlib import Path
import sys
from typing import Optional

homemanager_profile_tools_to_link: [str] = [
    "a8-versions",
    "chezmoi",
    "fish",
    "java",
    "pgbackrest",
    "runitor",
]

default_profile_tools_to_link: [str] = [
    "nix",
    "nix-build",
]

tools_to_link_str = " ".join(homemanager_profile_tools_to_link + default_profile_tools_to_link)

docs = f"""
this script sets up symlinks in /usr/local/bin for the various tools that we install via nix but
are needed system wide outside of users.

currently the following are linked {tools_to_link_str}
also a java11 link is made that points to java

Since this script makes changes to /usr/local/bin/ it must be run as root.

"""


overwrite = False


def logWarning(msg: str) -> None:
    print("WARNING !! " + msg)

def createSymlink(target: Path, link: Path) -> None:
    link_exists = link.exists()
    if not link.parent.exists():
        link.parent.mkdir(parents = True)
    if overwrite or not link_exists:
        if link_exists:
            link.unlink();
        if not target.exists():
            logWarning(f"target path does not exist @ {target}")
        else:
            print(f"creating symlink target={target}  link={link}")
            link.symlink_to(target)
    else:
        print(f"leaving {link} in place")

def linkNixTool(profile: Path, name: str, target_name: Optional[str] = None) -> None:
    if not target_name:
        target_name = name
    createSymlink(profile.joinpath(f"bin/{name}").resolve(), Path(f"/usr/local/bin/{target_name}"))

def run(overwrite0: bool) -> None:

    global overwrite
    overwrite = overwrite0

    homemanager_profile = Path("~homemanager").expanduser().joinpath(".nix-profile")
    for tool in homemanager_profile_tools_to_link:
        linkNixTool(homemanager_profile, tool)

    linkNixTool(homemanager_profile, "java", "java11")

    default_profile = Path("/nix/var/nix/profiles/default")
    for tool in default_profile_tools_to_link:
        linkNixTool(default_profile, tool)


def run_test(overwrite0: bool) -> None:
    global overwrite
    overwrite = overwrite0
    print(f"run {overwrite} {overwrite0}")


def main() -> None:

    import argparse
    parser = argparse.ArgumentParser(
        prog = 'link-nix-tools',
        description = docs,
    )
    # parser.add_argument("--run", help="do the actual thing", action='store_true')
    subparsers = parser.add_subparsers(dest="command", help='sub-commands')
    runParser = subparsers.add_parser("run", help='do the actual work and change the system')
    runParser.add_argument("--force", "-f", action='store_true', help='force the link creation i.e. overwrite existing links')
    subparsers.add_parser("help", help='print this help')
    args = parser.parse_args()
    if args.command == "run":
        run(args.force)
    elif args.command == "help":
        parser.print_help()
    else:
        badargs = " ".join(sys.argv[1:])
        print(f"don't know how to handle command of {args.command} in {badargs}")
        parser.print_help()


if __name__ == '__main__':
    main()