# -*- coding: utf-8 -*-
from setuphelpers import *

app_install_path = "/usr/lib/virtualbox/"
app_vbm = makepath(app_install_path, "VBoxManage")


def install():
    bin_name = glob.glob("virtualbox-*.deb")[0]

    
    
    # Avoid VMs to be shutted unexpectedly
    if isrunning("virtualbox") and not force:
        error("ERROR: VirtualBox is running")

    uninstall()
    
    update_apt()
    install_apt("linux-headers-amd64")
    install_deb(bin_name)

    # Remove all file extpack
    for file in glob.glob(makepath(app_install_path, "Oracle_VirtualBox_Extension_Pack-*.vbox-extpack")):
        print("Removing: %s" % file)
        remove_file(file)

    # Copy new extpack
    for ext in glob.glob("Oracle_VirtualBox_Extension_Pack-*.vbox-extpack"):
        print("Copying: %s to: %s" % (ext, app_install_path))
        filecopyto(ext, app_install_path)
        # Install new extpack
        try:
            print(
                run(
                    'echo y | "%s" extpack install --replace "%s" --accept-license=33d7284dc4a0ece381196fda3cfe2ed0e1e8e7ed7f27b9a9ebc4ee22e24bd23c'
                    % (app_vbm, ext)
                )
            )
        except:
            print(run('"%s" extpack cleanup' % (app_vbm)))
            print(
                run(
                    'echo y | "%s" extpack install --replace "%s" --accept-license=33d7284dc4a0ece381196fda3cfe2ed0e1e8e7ed7f27b9a9ebc4ee22e24bd23c'
                    % (app_vbm, ext)
                )
            )


def session_setup():
    print("Disabling: Auto update checks")
    run('"%s" setextradata global GUI/UpdateDate never' % app_vbm)


def uninstall():
    for p in control.impacted_process.split(',') :
        killalltasks(p)
    uninstall_apt("'virtualbox*'")
    autoremove_apt()
    if not installed_softwares("virtualbox"):
        if isdir(app_install_path):
            remove_tree(app_install_path)
