#!/usr/bin/python3
# -*- coding: utf-8 -*-
import libcalamares
import subprocess
from shutil import copy2
from distutils.dir_util import copy_tree
from os.path import join, exists
from libcalamares.utils import target_env_call, target_env_process_output

def pretty_name():
    return "Misc post-install configurations"

status = "Misc post-install configurations"

def pretty_status_message():
    return status

class ConfigController:
    def __init__(self):
        try:
            self.__root = libcalamares.globalstorage.value("rootMountPoint")
        except Exception as e:
            print(f"Error initializing root mount point: {e}")
            raise

    @property
    def root(self):
        return self.__root

    def terminate(self, proc):
        try:
            target_env_call(['killall', '-9', proc])
        except Exception as e:
            print(f"Error terminating process '{proc}': {e}")

    def copy_file(self, file):
        try:
            if exists("/" + file):
                copy2("/" + file, join(self.root, file))
        except Exception as e:
            print(f"Error copying file '{file}': {e}")

    def copy_folder(self, source, target):
        try:
            if exists("/" + source):
                copy_tree("/" + source, join(self.root, target))
        except Exception as e:
            print(f"Error copying folder from '{source}' to '{target}': {e}")

    def is_pkg_installed(self, pkg):
        """ Checks if a package is installed in the target environment. """
        try:
            result = target_env_process_output(['xbps-query', pkg])
            return result is not None  # Package exists if query returns any result
        except Exception as e:
            print(f"Error checking if package '{pkg}' is installed: {e}")
            return False

    def remove_pkg(self, pkg):
        try:
            target_env_process_output(['xbps-remove', '-Ry', pkg])
        except Exception as e:
            print(f"Error removing package '{pkg}': {e}")

    def umount(self, mp):
        try:
            subprocess.call(["umount", "-l", join(self.root, mp)])
        except Exception as e:
            print(f"Error unmounting '{mp}': {e}")

    def mount(self, mp):
        try:
            subprocess.call(["mount", "-B", "/" + mp, join(self.root, mp)])
        except Exception as e:
            print(f"Error mounting '{mp}': {e}")

    def rmdir(self, dir):
        try:
            subprocess.call(["rm", "-Rf", join(self.root, dir)])
        except Exception as e:
            print(f"Error removing directory '{dir}': {e}")

    def mkdir(self, dir):
        try:
            subprocess.call(["mkdir", "-p", join(self.root, dir)])
        except Exception as e:
            print(f"Error creating directory '{dir}': {e}")

    def run(self):
        try:
            # Remove CLI installers
            if exists(join(self.root, "usr/sbin/void-installer")):
                target_env_process_output(["rm", "-fv", "usr/sbin/void-installer"])

            if exists(join(self.root, "usr/sbin/pep-installer")):
                target_env_process_output(["rm", "-fv", "usr/sbin/pep-installer"])

            # Initialize package manager databases
            if libcalamares.globalstorage.value("hasInternet"):
                target_env_process_output(["xbps-install", "-Syy"])

            # Remove Calamares from target
            self.remove_pkg("calamares")
            if exists(join(self.root, "usr/share/applications/calamares.desktop")):
                target_env_call(["rm", "-fv", "usr/share/applications/calamares.desktop"])

            # Remove Emptty if LightDM is present
            if exists(join(self.root, "etc/lightdm/lightdm.conf")):
                if exists(join(self.root, "usr/bin/emptty")):
                    target_env_process_output(["rm", "-fv", "etc/runit/runsvdir/default/emptty"])
                    target_env_process_output(["rm", "-rfv", "etc/emptty"])
                    self.remove_pkg("emptty")

            # Update grub.cfg
            if exists(join(self.root, "usr/bin/update-grub")):
                target_env_process_output(["update-grub"])

            # Enable `menu_auto_hide` in grubenv if supported
            if exists(join(self.root, "usr/bin/grub-set-bootflag")):
                target_env_call(["grub-editenv", "-", "set", "menu_auto_hide=1", "boot_success=1"])

            # Enable doas if installed on target
            if exists(join(self.root, "usr/bin/doas")):
                doasconf = "permit nopass :root ||\npermit persist :wheel"
                with open(join(self.root, "etc/doas.conf"), 'w') as conf:
                    conf.write(doasconf)

            # Mark current kernel as automatically installed
            target_env_process_output(["xbps-pkgdb", "-m", "auto", "linux6.1"])

            # Remove linux-headers package if installed and ignore it in updates
            if self.is_pkg_installed("linux-headers"):
                self.remove_pkg("linux-headers")
            else:
                print("Package 'linux-headers' not installed, skipping removal.")

            ignorepkg = "ignorepkg=linux-headers"
            self.mkdir("etc/xbps.d/")
            with open(join(self.root, "etc/xbps.d/00-ignore.conf"), 'w') as conf:
                conf.write(ignorepkg)

            # Reconfigure all target packages
            target_env_process_output(["xbps-reconfigure", "-fa"])

        except Exception as e:
            print(f"Error during run process: {e}")
            raise

def run():
    """ Misc post-install configurations """
    try:
        config = ConfigController()
        return config.run()
    except Exception as e:
        print(f"Error in main run function: {e}")
        return None

