#!/bin/sh
''':'
py="$GIT_CINNABAR_PYTHON"
if test -z "$py"; then
  for py in python3 python2.7 python2; do
    "$py" -c "from mercurial import hg" >/dev/null 2>&1 && break
    py=
  done
fi
if test -z "$py"; then
  for py in python3 python2.7 python2; do
    command -v "$py" > /dev/null && break
    py=python3
  done
fi
exec "$py" "$0" "$@"
exit 1
'''

from __future__ import division
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__)))
sys.path.append(os.path.join(os.path.dirname(__file__), 'pythonlib'))

from cinnabar.githg import GitHgStore
from cinnabar.hg.repo import Remote
from cinnabar.remote_helper import (
    GitRemoteHelper,
    TagsRemoteHelper,
)
from cinnabar.util import (
    fsencode,
    run,
)


def main(args):
    if sys.platform == 'win32':
        # By default, sys.stdout on Windows will transform \n into \r\n, which
        # the calling git process won't recognize in our answers.
        import msvcrt
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    assert len(args) == 2
    remote = Remote(*(fsencode(a) for a in args))

    store = GitHgStore()

    if remote.url == b'tags:':
        helper = TagsRemoteHelper(store)
    else:
        helper = GitRemoteHelper(store, remote)
    helper.run()

    store.close()


if __name__ == '__main__':
    run(main, sys.argv[1:])
