#!/usr/bin/env python3

# Copyright 2023 Josh Holbrook
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

from argparse import ArgumentParser
from configparser import ConfigParser
import os
import os.path
import platform
import sys

CONFIG_PATH = os.environ.get(
    "KORBENWARE_CONFIG", os.path.expanduser("~/.config/korbenware/config.ini")
)

CONFIG = ConfigParser()

DEFAULTS = {"background": {}, "menu": {}, "python": {}}


if platform.system() == "Darwin":
    DEFAULTS["background"]["path"] = "/System/Library/Desktop Pictures"
    DEFAULTS["menu"]["path"] = "/Applications:/System/Applications:"
    DEFAULTS["menu"]["path"] += os.path.expanduser("~/Applications")
    DEFAULTS["menu"]["depth"] = "2"
    DEFAULTS["python"]["path"] = "/opt/homebrew/bin/python3"

    for directory in [
        "/Library/Desktop Pictures",
        "/System/Library/Desktop Pictures",
        os.path.expanduser(
            "~/Library/Application Support/com.apple.mobileAssetDesktop"
        ),
    ]:
        if os.path.isdir(directory):
            DEFAULTS["background"]["path"] += f":{directory}"

else:
    DEFAULTS["background"]["path"] = "/usr/share/backgrounds"
    DEFAULTS["background"]["sway_args"] = "fill"
    DEFAULTS["python"]["path"] = "/usr/bin/python3"


def log_info(msg):
    if os.environ.get("DEBUG"):
        print(f"info: {msg}")


parser = ArgumentParser()
parser.add_argument("action", choices=["init", "get", "set"])
parser.add_argument("section", nargs="?", choices=list(DEFAULTS.keys()), default=None)
parser.add_argument("key", nargs="?", default=None)
parser.add_argument("value", nargs="?", default=None)
parser.add_argument("--if-none", default=None)
parser.add_argument("--force", dest="force", action="store_true", default=False)

log_info("Korben's Cool Petsitter's Configuration Manager 🦜")
log_info("programmed entirely from the grave")
log_info("it worked if it ends with ok")

args = parser.parse_args()

if args.action == "init":
    if os.path.isfile(CONFIG_PATH) and not args.force:
        print(
            f"'{CONFIG_PATH}' is already initialized. "
            "Use the --force flag to override."
        )
        sys.exit(1)
    else:
        for section in DEFAULTS.keys():
            CONFIG[section] = {**DEFAULTS[section]}
        os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
        with open(CONFIG_PATH, "w") as f:
            CONFIG.write(f)
        print(f"Default configuration written to '{CONFIG_PATH}'.")
        sys.exit(0)

CONFIG.read(CONFIG_PATH)

if not (args.section and args.key):
    print("the following arguments are required: section, key")
    sys.exit(1)

if args.action == "get":
    value = {
        **DEFAULTS[args.section],
        **(CONFIG[args.section] if CONFIG.has_section(args.section) else {}),
    }.get(args.key, args.if_none)
    print(value)
elif args.action == "set":
    if args.value:
        CONFIG[args.section][args.key] = args.value
        with open(CONFIG_PATH, "w") as f:
            CONFIG.write(f)
else:
    print(f"Unknown action {args.action}")
    print("not ok")
    sys.exit(1)

log_info("ok")
