#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# === This file is part of Calamares - <http://github.com/calamares> ===
#
#   Copyright 2014 - 2019, Philip Müller <philm@manjaro.org>
#   Copyright 2016, Artoo <artoo@manjaro.org>
#
#   Calamares is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   Calamares is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with Calamares. If not, see <http://www.gnu.org/licenses/>.

import libcalamares
import subprocess

from shutil import copy2, copytree
from os.path import join, exists
from os import rename, makedirs
from libcalamares.utils import target_env_call, target_env_process_output


class ConfigController:
    def __init__(self):
        self.__root = libcalamares.globalstorage.value("rootMountPoint")
        self.__keyrings = libcalamares.job.configuration.get('keyrings', [])

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

    @property
    def keyrings(self):
        return self.__keyrings

    def init_keyring(self):
        target_env_call(["pacman-key", "--init"])

    def populate_keyring(self):
        target_env_call(["pacman-key", "--populate"])

    def terminate(self, proc):
        target_env_call(['killall', '-9', proc])

    def copy_file(self, file):
        if exists("/" + file):
            copy2("/" + file, join(self.root, file))

    def copy_folder(self, source, target):
        if exists("/" + source):
            copytree("/" + source, join(self.root, target), symlinks=True, dirs_exist_ok=True)

    def remove_pkg(self, pkg, path):
        if exists(join(self.root, path)):
            target_env_call(['pacman', '-R', '--noconfirm', pkg])

    def umount(self, mp):
        subprocess.call(["umount", "-l", join(self.root, mp)])

    def mount(self, mp):
        subprocess.call(["mount", "-B", "/" + mp, join(self.root, mp)])

    def rmdir(self, dir):
        subprocess.call(["rm", "-Rf", join(self.root, dir)])

    def mkdir(self, dir):
        subprocess.call(["mkdir", "-p", join(self.root, dir)])

    def find_xdg_directory(self, user, type):
        output = []
        target_env_process_output(["su", "-lT", user, "xdg-user-dir", type], output)
        return output[0].strip()

    def run(self):
        self.init_keyring()
        self.populate_keyring()

        # Remove unneeded ucode
        cpu_ucode = subprocess.getoutput("hwinfo --cpu | grep Vendor: -m1 | cut -d\'\"\' -f2")
        if cpu_ucode == "AuthenticAMD":
            self.remove_pkg("intel-ucode", "boot/intel-ucode.img")
        elif cpu_ucode == "GenuineIntel":
            self.remove_pkg("amd-ucode", "boot/amd-ucode.img")
        else:
            # Since no microcode packages were removed, dracut needs to be manually triggered
            target_env_call(["dracut-rebuild"])

        # Workaround for pacman-key bug
        # FS#45351 https://bugs.archlinux.org/task/45351
        # We have to kill gpg-agent because if it stays
        # around we can't reliably unmount
        # the target partition.
        self.terminate('gpg-agent')

        # Copy skel to root
        self.copy_folder('etc/skel', 'root')

        # create snapper config
        if exists(join(self.root, "usr/bin/snapper")):
            target_env_call(["snapper", "--no-dbus", "-c", "root", "create-config", "/"])
            if libcalamares.globalstorage.contains("garudaInplaceSnapshots"):
                btrfs_root = libcalamares.globalstorage.value("garudaInplaceBtrfsRoot")
                snapshots_location = libcalamares.globalstorage.value("garudaInplaceSnapshots")
                rename(join(btrfs_root, snapshots_location), join(btrfs_root, "@", ".snapshots"))
            else:
                target_env_call(["btrfs", "subvolume", "create", "/.snapshots"])

        # Move home files from old home to new home (into a subfolder)
        if libcalamares.globalstorage.contains("garudaInplaceHome"):
            subvol_old_home = libcalamares.globalstorage.value("garudaInplaceHome")
            username = libcalamares.globalstorage.value("username")
            chroot_desktop_path = self.find_xdg_directory(username, "DESKTOP")
            btrfs_root = libcalamares.globalstorage.value("garudaInplaceBtrfsRoot")
            chroot_destination_path = join(chroot_desktop_path, "Old_Home_Files")
            btrfsroot_destination_path = join(btrfs_root, "@home", chroot_destination_path.lstrip('/home/'))
            btrfsroot_old_home_path = join(btrfs_root, subvol_old_home)
            # Copy files with reflink from old home to desktop
            makedirs(btrfsroot_destination_path, exist_ok=True)
            subprocess.call(["cp", "-a", "--reflink=auto", btrfsroot_old_home_path + "/.", btrfsroot_destination_path])
            # Set ownership to user
            target_env_call(["chown", "-R", f"{username}:{username}", chroot_destination_path])
            if exists(join(btrfsroot_destination_path, "pre-reset-packages-backup.txt")):
                target_env_call(["mv", join(chroot_destination_path, "pre-reset-packages-backup.txt"),
                                 join(chroot_desktop_path, "pre-reset-packages-backup.txt")])

        return None


def run():
    """ Misc postinstall configurations """

    config = ConfigController()

    return config.run()
