#!/usr/bin/env python3
#
# Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018  Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Timeline is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Timeline.  If not, see <http://www.gnu.org/licenses/>.


from os import environ
from os.path import dirname, basename, join
import argparse
import glob
import json
import subprocess
import sys
import tempfile

import timelinetools.packaging.repository


def main():
    build_winows_exe(parse_arguments())


def parse_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument("--revision", default="tip")
    parser.add_argument("--output-list")
    return parser.parse_args()


def build_winows_exe(arguments):
    with tempfile.TemporaryDirectory(dir=".") as tempdir:
        build_winows_exe_tmp(arguments, tempdir)


def build_winows_exe_tmp(arguments, tempdir):
    zips = glob.glob(f"{environ.get('ZIP_DIR', '.')}/timeline-*.zip")
    if len(zips) != 1:
        sys.exit("ERROR: Could not find source zip.")
    archive = timelinetools.packaging.zipfile.ZipFile(
        dirname(zips[0]),
        basename(zips[0])
    ).extract_to(tempdir)
    subprocess.check_call([
        "wine",
        f"{environ['PYTHON_DIR']}\\python.exe",
        archive.get_path("tools/execute-specs.py"),
    ])
    archive.change_constant(
        "tools/winbuildtools/inno/timeline.iss",
        "AppVerName",
        f"Timeline {archive.get_version_number_string()}"
    )
    exe_name = f"{archive.get_filename_version()}-Win64Setup"
    archive.change_constant(
        "tools/winbuildtools/inno/timeline.iss",
        "OutputBaseFilename",
        exe_name
    )
    archive.change_constant(
        "source/timelinelib/config/paths.py",
        "_ROOT",
        '"."'
    )
    archive.clean_pyc_files()
    subprocess.check_call([
        "wine",
        f"{environ['PYTHON_DIR']}\\Scripts\\pyinstaller.exe",
        "timeline.spec",
    ], cwd=archive.get_path("tools/winbuildtools"))
    subprocess.check_call([
        "wineserver",
        "-w",
    ])
    subprocess.check_call([
        "cp",
        "-r",
        archive.get_path("translations"),
        archive.get_path("icons"),
        archive.get_path("tools/winbuildtools/dist"),
    ])
    subprocess.check_call([
        "wine",
        f"{environ['INNO_DIR']}\\ISCC.exe",
        "inno/timeline.iss",
    ], cwd=archive.get_path("tools/winbuildtools"))
    subprocess.check_call([
        "wineserver",
        "-w",
    ])
    subprocess.check_call([
        "mv",
        archive.get_path(f"tools/winbuildtools/inno/out/{exe_name}.exe"),
        f"{exe_name}.exe",
    ])
    write_output_list(
        arguments=arguments,
        exe_file=join(".", f"{exe_name}.exe"),
        version=archive.get_version_number_string(),
    )


def write_output_list(arguments, exe_file, version):
    if arguments.output_list:
        with open(arguments.output_list, "w") as f:
            f.write(json.dumps({
                "artifacts": [
                    {
                        "source": exe_file,
                        "destination": join(version, basename(exe_file)),
                    }
                ],
            }))


if __name__ == '__main__':
    main()
