#!/usr/bin/python3

"""Download maven packages needed to build kotlin.

This scripts downloads the minimal set of packages from maven repository needed
for building kotlin. Packages available in Debian repositories are not
downloaded.
"""

import subprocess
from pathlib import Path

KOTLIN_VERSION = '1.3.31'

PACKAGES = [
    ['org.jetbrains.kotlin', 'kotlin-gradle-plugin', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-gradle-plugin-api', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-gradle-plugin-model', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-native-utils', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-annotation-processing-gradle',
     KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-compiler', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-compiler-embeddable', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-compiler-runner', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-scripting-common', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-scripting-compiler', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-scripting-compiler-embeddable',
     KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-scripting-impl', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-scripting-jvm', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-script-runtime', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-reflect', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-stdlib', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-stdlib-common', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-daemon-client', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-build-common', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-android-extensions', KOTLIN_VERSION],
    ['org.jetbrains.kotlin', 'kotlin-sam-with-receiver', KOTLIN_VERSION],
    ['org.jetbrains.kotlinx', 'kotlinx-coroutines-core', '1.0.1'],
    ['org.jetbrains.kotlinx', 'kotlinx-metadata-jvm', '0.0.4'],
]


URL = 'https://repo1.maven.org/maven2/{group_path}/{name}/{version}/' \
    '{name}-{version}.{extension}'
URL2 = 'https://dl.bintray.com/kotlin/kotlinx/{group_path}/{name}/{version}/'\
    '{name}-{version}.{extension}'
BUILD_DIR = 'debian/tmp'
FILE = BUILD_DIR + '/usr/share/maven-repo/{group_path}/{name}/{version}/' \
    '{name}-{version}.{extension}'


def download_file(group, name, version, extension):
    """Download a single file from maven repositories."""
    clean_file(group, name, version, extension)

    group_path = group.replace('.', '/')
    url = URL if 'kotlinx' not in group else URL2
    url = url.format(group_path=group_path, name=name, version=version,
                     extension=extension)
    file = FILE.format(group_path=group_path, name=name, version=version,
                       extension=extension)
    parent = Path(file).parent
    parent.mkdir(parents=True, exist_ok=True)

    import wget
    wget.download(url, file, bar=None)


def fix_versions(group, name, version):
    """Fix dependency version for kotlinx-metadata-jvm."""
    replaces = {'kotlinx-metadata-jvm': ['1.2.50', KOTLIN_VERSION],
                'kotlin-compiler': ['1.0.20181211', 'debian'],
                'kotlin-compiler-embeddable': ['1.0.20181211', 'debian'],
                'kotlin-stdlib': ['13.0', 'debian']}
    if name not in replaces:
        return

    group_path = group.replace('.', '/')
    file = FILE.format(group_path=group_path, name=name, version=version,
                       extension='pom')
    old_version, new_version = replaces[name]
    command = ['sed', '-i', '-e', f's/{old_version}/{new_version}/', file]
    print('Running:', ' '.join(command))
    subprocess.run(command, check=True)


def clean_file(group, name, version, extension):
    """Remove a single file from the system."""
    group_path = group.replace('.', '/')
    file = FILE.format(group_path=group_path, name=name, version=version,
                       extension=extension)
    try:
        Path(file).unlink()
    except FileNotFoundError:
        pass


def install_package(group, name, version):
    """Download a dependency into /usr/share/maven-repo."""
    print(f'Downloading: :{group}:{name}:{version}')
    download_file(group, name, version, 'jar')
    download_file(group, name, version, 'pom')
    fix_versions(group, name, version)


def create_deb():
    """Generate basic kotlin .deb wrapper for bootstrap jars"""
    (Path(BUILD_DIR) / 'DEBIAN').mkdir(parents=True, exist_ok=True)

    command = ['dpkg-gencontrol', f'-P{BUILD_DIR}']
    print('Running:', ' '.join(command))
    subprocess.run(command, check=True)

    command = ['dpkg-deb', '--build', BUILD_DIR, '..']
    print('Running:', ' '.join(command))
    subprocess.run(command, check=True)


def main():
    """Check prerequisites before starting download."""
    try:
        import wget
    except ImportError:
        print('Script dependencies missing. Run:')
        print('sudo apt install wget python3-wget')
        exit(-1)

    print(f'Building in: {BUILD_DIR}')

    for package in PACKAGES:
        install_package(package[0], package[1], package[2])

    create_deb()


if __name__ == '__main__':
    main()
