#!/usr/bin/env python
"""
A wrapper script that implements an interface compatible with hgmerge.
Basically, it needs to exit with 0 on success, and to place the results of the
merge in the 'left' file.

Use it like this:

  [merge-patterns]
  ** = xx-hg-merge

"""

# stdlib imports
import sys, os, shutil, re

# xxdiff imports
from xxdiff import invoke
from xxdiff.scripts import encrypted


def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip())
    invoke.options_graft(parser)

    parser.add_option('-g', '--gpg', default="gpg",
                      help="Specify path to gpg program to use.")

    parser.add_option('-r', '--recipient', action='store',
                      help="Encrypt for user id name.")

    parser.add_option('-A', '--dont-armor', action='store_true',
                      help="Create output file in binary format.")

    opts, args = parser.parse_args()
    invoke.options_validate(opts, parser)

    if len(args) != 3:
        parser.error("You need to provide 3 arguments.")
    fl, fb, fr = args

    # Invoke xxdiff.
    mergedf = None
    if not re.match('.*\\.(asc|gpg)$', fl):
        decision, mergedf, __retcode = invoke.xxdiff_decision(
            opts,
            '--title1=Current',
            '--title2=Ancestor',
            '--title3=Merging',
            fl, fb, fr)
        merged_name = mergedf.name
    else:
        merged_name = '%s.merged' % fl
        textlist = [open(n).read() for n in (fl, fb, fr)]
        decision = encrypted.diff_encrypted(textlist, opts, merged_name)

    # If the user exited normally, copy the merged results to the left file
    # (because that's what the Mercurial merge.py code expects).
    if decision != 'NODECISION':
        shutil.copyfile(merged_name, fl)
        ret = 0
    else:
        ret = 1

    if mergedf is not None:
        mergedf.close()
    try:
        os.remove(merged_name)
    except (IOError, OSError):
        pass

    return ret


if __name__ == '__main__':
    sys.exit(main())


# From mercurial.merge, this program is invoked like tihs::
#
#     r = util.system('%s "%s" "%s" "%s"' % (cmd, a, b, c), cwd=repo.root,
#                     environ={'HG_FILE': fd,
#                              'HG_MY_NODE': str(wctx.parents()[0]),
#                              'HG_OTHER_NODE': str(mctx),
#                              'HG_MY_ISLINK': fcm.islink(),
#                              'HG_OTHER_ISLINK': fco.islink(),
#                              'HG_BASE_ISLINK': fca.islink(),})
#
# The following environment variables are defined by the caller script:
#
#   HG_FILE: the destination filename
#   HG_MY_NODE: ?
#   HG_OTHER_NODE: ?
#   HG_MY_ISLINK: ?
#   HG_OTHER_ISLINK: ?
#   HG_BASE_ISLINK: ?
