#!/usr/bin/env python
# -*- coding: utf-8 -*-
#--------------------------------------------------------------------------------

##
## Copyright (c) 2005-2011 Gemini Mobile Technologies, Inc.  All rights reserved.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
##     http:##www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##

import os, sys
import ConfigParser
import sets
import subprocess
import re

#--------------------------------------------------------------------------------
#   dprint
#--------------------------------------------------------------------------------
def dprint(msg):
    print >>sys.stderr, "a2xp:" + msg

#--------------------------------------------------------------------------------
#   get_options
#--------------------------------------------------------------------------------
def get_options(confs, section):
    opts = sets.Set()
    for conf in confs:
        if conf.has_section(section):
            opts |= sets.Set(conf.options(section))
    return opts

#--------------------------------------------------------------------------------
#   get_option_value
#--------------------------------------------------------------------------------
def get_option_value(confs, section, option):
    val = None
    for conf in confs:
        if conf.has_option(section, option):
            val = conf.get(section, option)
    return val

#--------------------------------------------------------------------------------
#   fix_path
#--------------------------------------------------------------------------------
def fix_path(base, path):
    ret = os.path.join(base, path)
    if sys.platform == 'cygwin':
        ret = subprocess.Popen(["cygpath", "-am", ret], stdout=subprocess.PIPE).communicate()[0]
    return ret.strip()

#--------------------------------------------------------------------------------
#   fix_dir
#--------------------------------------------------------------------------------
def fix_dir(base, path):
    return fix_path(base, path) + "/"

#--------------------------------------------------------------------------------
#   fix_val
#--------------------------------------------------------------------------------
def fix_val(val):
    ret = u""
    rest = val
    while rest != "":
        # example: &#x00a9;
        m = re.search('&#x([0-9a-fA-F]{4});', rest)
        if m:
            ret += rest[:m.start(0)]
            ret += hex_to_unicode(m.group(1))
            rest = rest[m.end(0):]
        else:
            ret += rest
            rest = ""

    return ret.encode("utf-8")

#--------------------------------------------------------------------------------
#   hex_to_unicode
#--------------------------------------------------------------------------------
def hex_to_unicode(hexstr):
    return unichr(int(hexstr, 16))

#--------------------------------------------------------------------------------
#   get_target_format
#--------------------------------------------------------------------------------
def get_target_format(args):
    trg_format = None
    rest = args
    while rest != []:
        if rest[0] == '-f':
            trg_format = rest[1]
        elif rest[0].startswith("--format="):
            trg_format = rest[0][9:]
        rest = rest[1:]
    return trg_format

#--------------------------------------------------------------------------------
#   a2x_pre
#--------------------------------------------------------------------------------
def a2x_pre():
    add_env = []
    add_opt = []
    outputs_dir = os.environ['OUTPUTS']
    trg_format = get_target_format(sys.argv)
    if trg_format == 'pdf':
        add_opt.append('--xsltproc-opts=--stringparam %s "%s"' % ("img.src.path", fix_dir(outputs_dir, "")))

    dstconf = ConfigParser.ConfigParser()
    defconf0 = ConfigParser.ConfigParser()
    defconf1 = ConfigParser.ConfigParser()
    dst = sys.argv[-1]
    dstdef = os.path.splitext(dst)[0] + '.def'
    dprint("a2x_pre: dstdef=%r" % dstdef)
    if os.path.isfile(dstdef):
        dstconf.read([dstdef])
        if dstconf.has_option('Document', 'xslstyle'):
            # handle xslstyle
            xslstyle = dstconf.get('Document', 'xslstyle')
            dprint("a2x_pre: xslstyle=%r" % xslstyle)
            add_env += [ "A2X_CONF_PATH=" + ':'.join([
                "%s/xslstyles/%s" % (os.path.abspath(os.environ['XSLSTYLE_PATH']), xslstyle),
                "%s/xslstyles/%s" % (os.environ['ADOC_ETC'], xslstyle),
            ]) ]
            # handle default.def on the xslstyle
            #   --xsltproc-opts="--stringparam PARAM VALUE"
            defdef0 = os.path.join(os.environ['ADOC_ETC'], "xslstyles", xslstyle, "default.def")
            defdef1 = os.path.join(os.path.abspath(os.environ['XSLSTYLE_PATH']), "xslstyles", xslstyle, "default.def")
        else:
            add_env += [ "A2X_CONF_PATH=" + ':'.join([
                "%s/xslstyles" % (os.path.abspath(os.environ['XSLSTYLE_PATH'])),
                "%s/xslstyles" % (os.environ['ADOC_ETC']),
            ]) ]
            defdef0 = os.path.join(os.environ['ADOC_ETC'], "xslstyles", "default.def")
            defdef1 = os.path.join(os.path.abspath(os.environ['XSLSTYLE_PATH']), "xslstyles", "default.def")
        dprint("a2x_pre: add_env=%r" % add_env)

        dprint("a2x_pre: defdef0=%r" % defdef0)
        dprint("a2x_pre: defdef1=%r" % defdef1)
        if os.path.isfile(defdef0):
            defconf0.read([defdef0])
            dprint("read defdef0: %r" % defdef0)
        if os.path.isfile(defdef1):
            defconf1.read([defdef1])
            dprint("read defdef1: %r" % defdef1)

    confs = [defconf0, defconf1, dstconf]
    path_xsl_params = get_options(confs, "path-xsl-param")
    for param in path_xsl_params:
        val = get_option_value(confs, "path-xsl-param", param)
        val = fix_path(outputs_dir, val)
        add_opt.append('--xsltproc-opts=--stringparam %s "%s"' % (param, val))

    xsl_params = get_options(confs, "xsl-param")
    for param in xsl_params:
        val = get_option_value(confs, "xsl-param", param)
        val = fix_val(val)
        add_opt.append('--xsltproc-opts=--stringparam %s "%s"' % (param, val))
    add_opt.append('--xsltproc-opts=--param toc.section.depth 3')
    dprint("a2x_pre: add_opt=%r" % add_opt)

    return add_env, add_opt

#--------------------------------------------------------------------------------
#   main
#--------------------------------------------------------------------------------
def main():
    env_bin = "/usr/bin/env"
    add_env = []
    add_opt = []
    adoc_vers = os.environ.get('ADOC_VERSION', "")
    dprint("a2xp: adoc_vers=%r" % adoc_vers)
    if adoc_vers.startswith("8.4.4"):
        add_env, add_opt = a2x_pre()
    os.execv(env_bin, [env_bin] + add_env + [sys.argv[1]] + add_opt + sys.argv[2:])

#--------------------------------------------------------------------------------
#   MAIN
#--------------------------------------------------------------------------------
if __name__ == '__main__':
    main()

# END
