#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#   SPDX-FileCopyrightText: 2020 Arjen Balfoort <solydxk.abalfoort@tuta.com>
#   SPDX-License-Identifier: GPL-3.0-or-later
#

import os
import sys
import subprocess
import apt
import libcalamares

CACHE = apt.Cache()


def install_regional(lang):
    """
    Install regional packages for language

    Args:
        lang (str): Language (e.g.: ja_JP)
    """
    # Get packages for language
    locale_path = f"/usr/lib/solydxk/system/localize/{lang}"
    if not os.path.exists(locale_path):
        libcalamares.utils.debug(f"Localization file not found: {locale_path} - skipping")
        return

    # Check if KDE Plasma is installed
    kde_plasma = os.path.exists("/etc/xdg/plasma-workspace") or \
                    any("plasma-workspace" in line for line in
                    os.popen("dpkg -l").read().splitlines())

    with open(file=locale_path, mode='r', encoding='utf-8') as f:
        for line in f.readlines():
            if line.startswith('all='):
                packages = line.split('=')[1].strip().split()
            if kde_plasma and line.startswith('qt='):
                packages += line.split('=')[1].strip().split()

    # Start installing
    for package in packages:
        if not CACHE[package].is_installed:
            try:
                libcalamares.utils.debug(f"Install additional package "
                                            f"for language {lang}: {package}")
                libcalamares.utils.check_target_env_call(
                    ["apt-get", "-q", "-y", "install", package])
            finally:
                libcalamares.utils.debug(
                    f"Install additional package finished: {package}")

def remove_virtguest():
    """
    Remove VirtualBox and Qemu Guest packages when not in VirtualBox
    """
    virt = (subprocess.run('systemd-detect-virt',
                           check=False,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)
            .stdout.decode(sys.getfilesystemencoding()).strip())

    if 'oracle' not in virt:
        # Remove VirtualBox Guest packages
        libcalamares.utils.check_target_env_call(
            ["apt-get", "--purge", "-q", "-y", "remove", "virtualbox-guest*"])

    if 'kvm' not in virt:
        # Remove Qemu Guest packages
        libcalamares.utils.check_target_env_call(
            ["apt-get", "--purge", "-q", "-y", "remove", "qemu-guest*"])
        libcalamares.utils.check_target_env_call(
            ["apt-get", "--purge", "-q", "-y", "remove", "spice-vdagent*"])

def run():
    """Install localized packages

    Returns:
        object: None on finished
    """

    # Only continue when having an internet connection
    skip_this = libcalamares.job.configuration.get(
        "skip_if_no_internet", False)
    if skip_this and not libcalamares.globalstorage.value("hasInternet"):
        libcalamares.utils.warning("Package installation has been skipped: "
                                   "no internet")
        return None

    # Get user selected language
    lang = libcalamares.globalstorage.value("localeConf")["LANG"].split(".")[0]
    if not lang or lang == "en_US":
        return None

    # Install regional packages for lang
    install_regional(lang)

    # Remove VB Guest when not in VB
    remove_virtguest()

    return None
