#!env python
#
# Copyright (C) 2015 shimoda
#
# 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 sys
import os
import StringIO
from ConfigParser import SafeConfigParser
import logging
from logging import error as eror, info
from urlparse import urlparse


def main():
    dproj = options()
    drepo = os.path.join(dproj, "..", "..")
    drepo = os.path.abspath(drepo)

    url = ""
    for func in (main_hg, main_git):
        url = func(drepo)
        if url:
            break
    else:
        raise RuntimeError()
    main_parse_and_gen(drepo, url)


def options():
    log = logging.getLogger("")
    log.setLevel(logging.INFO)
    return sys.argv[1]


def main_hg(drepo):                                         # {{{1
    fname = os.path.join(drepo, ".hg", "hgrc")
    fname = os.path.abspath(fname)
    if not os.path.isfile(fname):
        info(".hgrc not found and skip...")
        return ""

    info("parse '%s'" % fname)
    cfg = SafeConfigParser()
    cfg.read(fname)
    if not cfg.has_section("paths"):
        eror("?? .hgrc has no section [paths], ignored.")
        return ""

    for opt in cfg.options("paths"):
        v = cfg.get("paths", opt)
        if (v.startswith("git://") or
                v.startswith("git+ssh://")):
            return v     # use 1st URL to git.
    return ""


def main_parse_and_gen(dname, url):
    info("use url as: %s" % url)
    for parser in (parse_github, parse_bitbucket):
        url_src, url_files = parser(url)
        if url_src:
            break
    else:
        raise RuntimeError(
            "can't parse hosting service %s by this program." % url)

    fname = os.path.join(dname, "android", "PythonForAndroid",
                         "src", "com", "googlecode",
                         "pythonforandroid", "PythonUrls.java")
    main_gen(fname, "", url_src, url_files)
    fname = os.path.join(dname, "android", "Python3ForAndroid",
                         "src", "com", "googlecode",
                         "python3forandroid", "Python3Urls.java")
    main_gen(fname, "3", url_src, url_files)


def main_gen(fname, classname, url_src, url_files):
    info("write to java source => %s" % os.path.basename(fname))
    fp = file(fname, "w")
    fp.write('''/*
 * Copyright (C) 2015 shimoda
 *
 * !!do not edit!!
 * this file is automatically generated by gradle and python script.
 */
package com.googlecode.python%sforandroid;

public class Python%sUrls {
    public static final String URL_BIN =
        "%s";
    public static final String URL_SRC =
        "%s";
}
''' % (classname, classname, url_files, url_src))
    fp.close()
    return True


def main_git(drepo):                                        # {{{1
    fname = os.path.join(drepo, ".git", "config")
    fname = os.path.abspath(fname)
    if not os.path.isfile(fname):
        info(".git/config not found and skip...: %s" % fname)
        return ""

    info("parse '%s'" % fname)
    src = ""
    for line in file(fname):
        if line.startswith("\t"):
            line = line.lstrip()
        src += line
    src = StringIO.StringIO(src)
    cfg = SafeConfigParser()
    cfg.readfp(src)

    for sec in cfg.sections():
        info("check %s..." % sec)
        if not sec.startswith("remote "):
            continue
        name = sec[7:]
        name = name.strip('"')
        if not cfg.has_option(sec, "url"):
            continue
        url = cfg.get(sec, "url")
        if not url.startswith("git://"):
            continue
        return url

    info("can't found the git server definition.")
    return ""


def parse_github(url):                                      # {{{1
    up = urlparse(url)
    if up.netloc not in ("github.com", "git@github.com"):
        return None, None
    info("determined github: %s" % url)

    url_files = ("https://github.com" + up.path +
                 "/releases/download/")
    url_src = ("https://raw.githubusercontent.com" + up.path +
               "/master/")
    return url_src, url_files


def parse_bitbucket(url):                                   # {{{1
    up = urlparse(url)
    if up.netloc != "bitbucket.com":
        return None, None
    info("determined bitbucket: %s" % url)
    raise RuntimeError("parsing Bitbucket URL is not implemented.")
    return None, None


if __name__ == "__main__":
    main()
# vi: ft=python:et:ts=4:nowrap

@@ -602,16 +602,120 @@
 port os%0A
+import logging%0Afrom logging import error as eror, info%0A%0A%0Aif sys.version_info%5B0%5D == 2:%0A    from StringIO 
 import S
@@ -722,16 +722,20 @@
 tringIO%0A
+    
 from Con
@@ -772,71 +772,150 @@
 ser%0A
-import logging%0Afrom logging import error as eror, info%0A
+    from urlparse import urlparse%0Aelse:%0A    from io import StringIO%0A    from configparser import ConfigParser as SafeConfigParser%0A    
 from url
 pars
@@ -902,32 +902,36 @@
 ser%0A    from url
+lib.
 parse import url
@@ -936,16 +936,32 @@
 rlparse%0A
+    file = open%0A
 %0A%0Adef ma
@@ -3770,17 +3770,8 @@
 c = 
-StringIO.
 Stri

build script was updated for python3