#! /usr/bin/env python
# system-switch-java - the Java toolset switcher frontend
# Copyright (C) 2007 Red Hat, Inc.

# This program 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 2 of the License, or
# (at your option) any later version.

# This program 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 this program; see the file COPYING.  If not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA.

import os
import os.path
import signal
import sys

DIRECTORY = '/usr/share/system-switch-java/'
if not DIRECTORY in sys.path:
    sys.path.append(DIRECTORY)
from switch_java_functions import *

def main():
    show_gui = 0
    try:
        if os.access(DIRECTORY + 'switch_java_gui.py', os.R_OK):
            if os.environ['DISPLAY'] != '':
                show_gui = 1
    except:
        pass
    if os.path.basename(sys.argv[0]) == 'system-switch-java-tui':
        show_gui = 0
    if os.getuid() != 0:
        show_dialog(show_gui, ROOT_MESSAGE)
        sys.exit(1)
    # Get list of installed Java alternatives.
    java_list = get_java_list()
    if len(java_list) == 0:
        show_dialog(show_gui, NO_JAVA_MESSAGE)
        sys.exit(1)
    # Get default Java alternative.
    default_java_command = get_default_java_command()
    if default_java_command is None:
        show_dialog(show_gui, ETC_JAVA_MESSAGE)
        sys.exit(1)
    else:
        if default_java_command not in ALTERNATIVE_TO_COMMAND.values():
            show_dialog(show_gui,
                        NOT_RECOGNIZED_MESSAGE % default_java_command)
            sys.exit(1)
    default_java = COMMAND_TO_ALTERNATIVE[default_java_command]
    pretty_names = get_pretty_names(java_list)
    if show_gui:
        from switch_java_gui import mainDialog
    else:
        from switch_java_tui import mainDialog
    mainDialog().main(java_list, default_java, pretty_names)

def show_dialog(show_gui, message):
    if show_gui:
        from switch_java_gui import mainDialog
    else:
        from switch_java_tui import mainDialog
    mainDialog().show_dialog(message)

if __name__ == '__main__':
    # Make Ctrl-C work.
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    main()
    sys.exit(0)
