#!/usr/bin/env python

# VBoxGtk: A VirtualBox GTK+ GUI
# Copyright (C) 2008 Francisco J. Vazquez-Araujo, Spain
# franjva at gmail dot com

# This file is part of VBoxGtk.

# VBoxGtk 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.

# VBoxGtk 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 VBoxGtk.  If not, see <http://www.gnu.org/licenses/>.


"""
VBoxGtk executable.

Invokes the main function of the vboxgtk module after preparing the search
path. This is done by looking at the content of /etc/vbox/vbox.cfg. If the
file is not found, the script tries with /usr/lib/virtualbox-ose and
/opt/VirtualBox. If none exists the script will try to start the program
anyway (hoping that the user has added the necessary paths to PYTHONPATH).
"""


import os
import sys
import textwrap


def prepare_sys_path():
    vbox_install_path = None
    vbox_cfg_file = '/etc/vbox/vbox.cfg'
    if os.path.isfile(vbox_cfg_file):
        with open(vbox_cfg_file, 'r') as f:
            head = 'INSTALL_DIR='
            for line in f:
                if line.startswith(head):
                    vbox_install_path = line.lstrip(head).rstrip('\n')
                    break
    else:
        dir_list = ('/usr/lib/virtualbox-ose',
                    '/opt/VirtualBox')
        for d in dir_list:
            if os.path.isdir(d):
                vbox_install_path = d
                break
    if vbox_install_path is not None:
        vbox_install_path = os.path.abspath(vbox_install_path)
        sys.path.insert(0, vbox_install_path)
        sdk_dir = 'sdk/bindings/xpcom/python'
        sys.path.insert(0, os.path.join(vbox_install_path, sdk_dir))
    base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    if os.path.isdir(os.path.join(base_path, 'vboxgtk')):
        sys.path.insert(0, base_path)


def test_xpcom_import():
    msg = """
    You\'ll have to set the PYTHONPATH environment variable by hand to
    point to the locations of the VBoxPython.so module and of the xpcom sdk
    package (the former is usually at the base install directory of
    VirtualBox, the latter in its sdk/bindings/xpcom/python subdirectory).
    Otherwise this program will not run.
    """
    try:
        import xpcom.vboxxpcom
    except ImportError as ex:
        print "ERROR: xpcom package not found\n" + textwrap.dedent(msg)
        raise ex    
    except Exception as ex:
        print "ERROR: exception importing xpcom\n" + textwrap.dedent(msg)
        raise ex


prepare_sys_path()
test_xpcom_import()
import vboxgtk
vboxgtk.main()
