#!/usr/bin/env python

from optparse import OptionParser
from os.path import abspath, dirname, join
from subprocess import call
from sys import argv, stdout

from install.util import (
    MAJOR_VERSION,
    MINOR_VERSION,
    PLATFORM_MACX,
    PLATFORM_UNIX,
    PLATFORM_WIN32,
    REVISION,
    getPlatform,
    getTemplatesDirectory,
    writeTemplate
)

def main():
    parser = OptionParser("usage: %prog [options] [qmake-args]")
    parser.add_option("--bin-dir", action="store", default=None, dest="binDir",
                      help="Install directory for synthclone executable")
    parser.add_option("--build-dir", action="store", default=None,
                      dest="buildDir", help="Build directory")
    parser.add_option("--data-dir", action="store", default=None,
                      dest="dataDir",
                      help="Install directory for general data files")
    parser.add_option("--data-root-dir", action="store", default=None,
                      dest="dataRootDir", help="Install root for data files")
    parser.add_option("--debug", action="store_true", default=False,
                      dest="debug", help="Build a debug executable")
    parser.add_option("--doc-dir", action="store", default=None, dest="docDir",
                      help="Install directory for synthclone documentation")
    parser.add_option("--exec-prefix", action="store", default=None,
                      dest="execPrefix",
                      help="Install prefix for executable data")
    parser.add_option("--include-dir", action="store", default=None,
                      dest="includeDir",
                      help="Install directory for system header files")
    parser.add_option("--lib-dir", action="store", default=None, dest="libDir",
                      help="Install directory for synthclone shared library")
    parser.add_option("--make-dir", action="store", default=None,
                      dest="makeDir", help="Make directory")
    parser.add_option("--plugin-dir", action="store", default=None,
                      dest="pluginDir",
                      help="Install directory for synthclone plugins")
    parser.add_option("--prefix", action="store", default=None, dest="prefix",
                      help="Install prefix")
    parser.add_option("--qmake", action="store", default="qmake", dest="qmake",
                      help="location of Qt4 qmake executable")
    parser.add_option("--skip-api-docs", action="store", default=0,
                      dest="skipAPIDocs", help="Don't build API documentation",
                      type="int")
    parser.add_option("--skip-fader", action="store", default=0,
                      dest="skipFader", help="Don't build the fader plugin",
                      type="int")
    parser.add_option("--skip-headers", action="store", default=0,
                      dest="skipHeaders", help="Don't build API headers",
                      type="int")
    parser.add_option("--skip-hydrogen", action="store", default=0,
                      dest="skipHydrogen",
                      help="Don't build the Hydrogen plugin", type="int")
    parser.add_option("--skip-jack", action="store", default=0,
                      dest="skipJACK", help="Don't build the JACK plugin",
                      type="int")
    parser.add_option("--skip-lv2", action="store", default=0, dest="skipLV2",
                      help="Don't build the LV2 plugin", type="int")
    parser.add_option("--skip-portmedia", action="store", default=0,
                      dest="skipPortMedia",
                      help="Don't build the PortMedia plugin", type="int")
    parser.add_option("--skip-renoise", action="store", default=0,
                      dest="skipRenoise", help="Don't build the Renoise plugin",
                      type="int")
    parser.add_option("--skip-reverser", action="store", default=0,
                      dest="skipReverser",
                      help="Don't build the reverser plugin")
    parser.add_option("--skip-sample-loader", action="store", default=0,
                      dest="skipSampleLoader",
                      help="Don't build the sample loader plugin", type="int")
    parser.add_option("--skip-sfz", action="store", default=0, dest="skipSFZ",
                      help="Don't build the SFZ plugin", type="int")
    parser.add_option("--skip-trimmer", action="store", default=0,
                      dest="skipTrimmer",
                      help="Don't build the trimmer plugin", type="int")
    parser.add_option("--skip-zone-generator", action="store", default=0,
                      dest="skipZoneGenerator",
                      help="Don't build the zone generator plugin", type="int")
    options, args = parser.parse_args()

    platform = getPlatform()
    platformArgs = []
    if platform == PLATFORM_MACX:
        platformArgs += ["-spec", "macx-g++"]
        platformStr = "MACX"
    elif platform == PLATFORM_WIN32:
        platformStr = "WIN32"
    else:
        platformStr = "UNIX"

    scriptDir = abspath(dirname(argv[0]))

    buildDir = options.buildDir
    if buildDir is None:
        buildDir = "build"
    buildDir = abspath(join(scriptDir, buildDir))

    makeDir = options.makeDir
    if makeDir is None:
        makeDir = "make"
    makeDir = abspath(join(scriptDir, makeDir))

    prefix = options.prefix
    if prefix is None:
        prefix = "/usr/local"
    else:
        prefix = abspath(prefix)

    dataRootDir = options.dataRootDir
    if dataRootDir is None:
        dataRootDir = "share"
    dataRootDir = abspath(join(prefix, dataRootDir))

    execPrefix = options.execPrefix
    if execPrefix is None:
        execPrefix = prefix
    else:
        execPrefix = abspath(execPrefix)

    binDir = options.binDir
    if binDir is None:
        binDir = "bin"
    binDir = abspath(join(execPrefix, binDir))

    dataDir = options.dataDir
    if dataDir is None:
        dataDir = dataRootDir
    else:
        dataDir = abspath(join(prefix, dataDir))

    docDir = options.docDir
    if docDir is None:
        docDir = "doc"
    docDir = abspath(join(dataRootDir, docDir))

    includeDir = options.includeDir
    if includeDir is None:
        includeDir = "include"
    includeDir = abspath(join(prefix, includeDir))

    libDir = options.libDir
    if libDir is None:
        libDir = "lib"
    libDir = abspath(join(execPrefix, libDir))

    pluginDir = options.pluginDir
    if pluginDir is None:
        pluginDir = join("lib", "synthclone", "plugins")
    pluginDir = abspath(join(execPrefix, pluginDir))

    qmakeExecutable = options.qmake

    # Write config.h
    data = {
        "majorVersion": MAJOR_VERSION,
        "minorVersion": MINOR_VERSION,
        "platform": platformStr,
        "revision": REVISION
    }
    writeTemplate(join(scriptDir, "src", "include", "synthclone", "config.h"),
                  join(getTemplatesDirectory(), "config.h"), data)

    # Run `qmake`
    qmakeArgs = [qmakeExecutable, "-recursive"] + platformArgs + args + \
        ["MAJOR_VERSION=%d" % MAJOR_VERSION, "MINOR_VERSION=%d" % MINOR_VERSION,
         "REVISION=%d" % REVISION, "BUILDDIR=%s" % buildDir,
         "MAKEDIR=%s" % makeDir, "PREFIX=%s" % prefix,
         "DATAROOTDIR=%s" % dataRootDir, "EXECPREFIX=%s" % execPrefix,
         "BINDIR=%s" % binDir, "DATADIR=%s" % dataDir, "DOCDIR=%s" % docDir,
         "INCLUDEDIR=%s" % includeDir, "LIBDIR=%s" % libDir,
         "PLUGINDIR=%s" % pluginDir]
    if options.debug:
        qmakeArgs.append("DEBUG=1")
    if options.skipAPIDocs:
        qmakeArgs.append("SKIP_API_DOCS=1")
    if options.skipFader:
        qmakeArgs.append("SKIP_FADER_PLUGIN=1")
    if options.skipHeaders:
        qmakeArgs.append("SKIP_HEADERS=1")
    if options.skipHydrogen:
        qmakeArgs.append("SKIP_HYDROGEN_PLUGIN=1")
    if options.skipJACK:
        qmakeArgs.append("SKIP_JACK_PLUGIN=1")
    if options.skipLV2:
        qmakeArgs.append("SKIP_LV2_PLUGIN=1")
    if options.skipPortMedia:
        qmakeArgs.append("SKIP_PORTMEDIA_PLUGIN=1")
    if options.skipRenoise:
        qmakeArgs.append("SKIP_RENOISE_PLUGIN=1")
    if options.skipReverser:
        qmakeArgs.append("SKIP_REVERSER_PLUGIN=1")
    if options.skipSampleLoader:
        qmakeArgs.append("SKIP_SAMPLE_LOADER_PLUGIN=1")
    if options.skipSFZ:
        qmakeArgs.append("SKIP_SFZ_PLUGIN=1")
    if options.skipTrimmer:
        qmakeArgs.append("SKIP_TRIMMER_PLUGIN=1")
    if options.skipZoneGenerator:
        qmakeArgs.append("SKIP_ZONE_GENERATOR_PLUGIN=1")

    try:
        result = call(qmakeArgs)
    except Exception as e:
        parser.error("%s call failed: %s" % (qmakeExecutable, str(e)))
    if result:
        parser.error("%s returned an error" % qmakeExecutable)

    stdout.write("Configure successful.  Run `make` to build, and "
                 "`make install` to install.\n")

if __name__ == "__main__":
    main()
