#!/usr/bin/python -u

import sys

sys.path.append("/usr/lib/eroaster")

from os import environ, popen
from constants import title, version, year
from main import Application
from tools import striplist, which, TRUE, FALSE
from log4py import Category, LOGLEVEL_VERBOSE

cat = Category()
cat.set_loglevel(LOGLEVEL_VERBOSE)

if not environ.has_key("EROASTERINSTALL"):                  # when installing eroaster, do not fire up the interface

    mkisofs = FALSE
    readcd = FALSE
    cdrecord = FALSE
    isoinfo = FALSE
    cdda2wav = FALSE

    cat.info("%s %s starting up" % (title, version))

    # Checking username
    uname = environ["USER"]
    if (uname != "root"):
        cat.warn("You are %s - you may want to be root" % uname)
    else:
        cat.info("You are %s - that's fine" % uname)

    cat.info("Checking for required programs")

    if (which("mkisofs")) != "": 
        mkisofs = TRUE
    else:
        cat.error("Couldn't find mkisofs")
    if which("cdrecord") != "": 
        cdrecord = TRUE
    else:
        cat.error("Couldn't find cdrecord")
    if (which("isoinfo") != ""):
        isoinfo = TRUE
    else:
        cat.error("Couldn't find isoinfo")
    if (which("readcd") != ""):
        readcd = TRUE
    else:
        cat.error("Couldn't find readcd")
    if (which("cdda2wav") != ""):
        cdda2wav = TRUE
    else:
        cat.error("Couldn't find cdda2wav")

    if (mkisofs == TRUE):
        # Check wether mkisofs supports -gui
        pipe = popen("mkisofs 2>&1 | grep gui")
        output = striplist(pipe.readlines())
        pipe.close()

        if (len(output) == 0):
            mkisofssupportsgui = FALSE
        else:
            mkisofssupportsgui = TRUE

    # Check for additional programs
    cat.info("Checking for additional programs")

    # Check for mpg123ss
    if (which("mpg123") == ""):
        cat.warn("Couldn't find mpg123")

    # Check for ogg123
    if (which("ogg123") == ""):
        cat.warn("Couldn't find ogg123")

    # Check for ogginfo
    if (which("ogginfo") == ""):
        cat.warn("Couldn't find ogginfo")

    # Check for sox
    if (which("sox") == ""):
        cat.warn("Couldn't find sox")

    # Check for xmms
    if (which("xmms") == ""):
        cat.warn("Couldn't find xmms")

    # Check for freeamp
    if (which("freeamp") == ""):
        cat.warn("Couldn't find freeamp")
        
    # Check for normalize
    if (which("normalize") == ""):
        cat.warn("Couldn't find normalize")

    if (mkisofs == FALSE) or (cdrecord == FALSE) or (isoinfo == FALSE) or (readcd == FALSE) or (cdda2wav == FALSE):
        cat.error("One or more required programs couldn't be found.")
        sys.exit(1)
        
    # Start the app
    app = Application(mkisofssupportsgui)
    app.main()
