#!/usr/bin/python3 -u

import argparse
import os
import sys

import requests


args = None


def sanity_check(jar_dir, josm_symlink):
    if not os.path.exists(jar_dir):
        print(
               "JAR directory does not exist: %s" % jar_dir,
               file=sys.stderr,
             )

        return False

    if not os.access(jar_dir, os.W_OK):
        print(
               "JAR directory is not writable: %s" % jar_dir,
               file=sys.stderr,
             )

        return False

    if not os.path.isdir(jar_dir):
        print(
               "JAR directory is not a directory: %s" % jar_dir,
               file=sys.stderr,
             )

        return False

    if(
        os.path.lexists(josm_symlink) and
        not os.path.islink(josm_symlink)
      ):
        print(
               "JOSM symlink is not a symlink: %s" % josm_symlink,
               file=sys.stderr,
             )

        return False

    return True


def josm_installer():
    josm_symlink = os.path.join(
                       args.jar_dir,
                       'josm.jar',
                   )

    if not sanity_check(args.jar_dir, josm_symlink):
        sys.exit(1)

    if args.latest:
        variant = 'latest'
    else:
        variant = 'tested'

    version_url = (
                    'https://josm.openstreetmap.de/'
                    'wiki/TestedVersion?format=txt'
                  )

    jar_url = 'https://josm.openstreetmap.de/josm-%s.jar' % variant

    if args.verbose:
        print("Installing %s JOSM" % variant)

    s = requests.Session()

    if args.latest:
        local_file = os.path.join(
                         args.jar_dir,
                         'josm-%s.jar' % (
                             variant,
                         ),
                     )
    else:
        if args.debug:
            print("GET %s" % version_url)

        r = s.get(version_url)

        if r.status_code != requests.codes.ok:
            print("Error: Request failed: %s (%s %s)" % (
                    version_url,
                    r.status_code,
                    r.reason,
                ),
                file=sys.stderr,
            )
            sys.exit(1)

        if args.debug:
            print(r.text)

        version = r.text

        local_file = os.path.join(
                         args.jar_dir,
                         'josm-%s-%s.jar' % (
                             variant,
                             version,
                         ),
                     )

    download = True

    if os.path.exists(local_file) and not args.latest:
        if args.verbose:
            print("JOSM %s already downloaded: %s" % (
                    '%s %s' % (variant, version),
                    local_file,
                )
            )

        if not args.force:
            download = False

    if not download:
        sys.exit(0)

    if(
        (
          os.path.exists(local_file) and
          not os.access(local_file, os.W_OK)
        ) or
        (
          not os.path.exists(local_file) and
          not os.access(os.path.dirname(local_file), os.W_OK)
        )
      ):
        print("Error: Cannot write: %s" % local_file, file=sys.stderr)
        sys.exit(1)

    if args.verbose:
        print("Downloading: %s" % jar_url)

    r = s.get(jar_url)

    if r.status_code != requests.codes.ok:
        print("Error: Request failed: %s (%s %s)" % (
                version_url,
                r.status_code,
                r.reason,
            ),
            file=sys.stderr,
        )
        sys.exit(1)

    if args.verbose:
        print("Updating JAR file: %s" % local_file)

    with open(local_file, 'wb') as f:
        f.write(r.content)
        f.flush()

    if args.verbose:
        print("Update symlink: %s" % josm_symlink)

    if os.path.lexists(josm_symlink):
        os.remove(josm_symlink)

    os.symlink(local_file, josm_symlink)


def main():
    global args

    default = {
                'jar-dir': '/usr/share/josm',
              }

    parser = argparse.ArgumentParser()

    parser.add_argument(
                         '-J', '--jar-dir',
                         metavar='<PATH>',
                         action='store',
                         help='Path to store JAR file (default: %s)' % (
                             default['jar-dir'],
                         ),
                         default=default['jar-dir'],
                       )
    parser.add_argument(
                         '-L', '--latest',
                         action='store_true',
                         help='Install latest instead of tested',
                       )
    parser.add_argument(
                         '-f', '--force',
                         action='store_true',
                         help='Force download',
                       )
    parser.add_argument(
                         '-d', '--debug',
                         action='store_true',
                         help='Enable debug output',
                       )
    parser.add_argument(
                         '-v', '--verbose',
                         action='store_true',
                         help='Enable verbose output',
                       )

    args = parser.parse_args()

    if not args.jar_dir:
        print("Error: No JAR dir specified!", file=sys.stderr)
        sys.exit(1)

    josm_installer()


if __name__ == "__main__":
    main()
