#!/usr/bin/python3

# Copyright (C) 2019-2020  Patryk Obara <patryk.obara@gmail.com>
# SPDX-License-Identifier: GPL-2.0-or-later
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# pylint: disable=invalid-name
# pylint: disable=missing-docstring

import argparse
import os
import subprocess
import sys

import confgen
import fakescripteval
import midi
import preconfig
import toolbox
import tweaks
import version

from fakesierralauncher import SierraLauncherConfig
from log import log, log_err, log_warn
from settings import SETTINGS as settings


def setup_midi():
    """Handle whole MIDI setup based on user preference."""
    game_id = toolbox.get_game_global_id()
    midi_preset = tweaks.get_midi_preset(game_id)

    midi_on = settings.get_midi_on()
    detected_sf2 = settings.get_midi_soundfont()
    detected_external_synth = midi.detect_external_synth()

    if midi_on and (not detected_sf2) and (not detected_external_synth):
        settings.set_midi_on(False)

    if midi_preset == 'disable':
        log('this game does not support MIDI music')
        settings.set_midi_on(False)

    if midi_preset == 'auto':
        setup_midi_for_game()

    if not detected_external_synth:
        midi.start_midi_synth()


def setup_midi_for_game():
    """Configure game to use (or not) MIDI."""

    if not preconfig.verify():
        log_err('checksum on resource file failed')
        return

    rfile_name = preconfig.find_resource_file()
    log('using resource file', rfile_name)
    with preconfig.open_resource(rfile_name) as rfile:
        steam_app_id = os.environ.get('SteamAppId', '0')
        if not rfile.includes(steam_app_id):
            log_err('resource file does not include files for', steam_app_id)
            return
        x = 'on' if settings.get_midi_on() else 'off'
        log('turning MIDI {} for {}'.format(x, steam_app_id))
        rfile.extract(steam_app_id, 'midi_' + x)
        rfile.apply_rpatch(steam_app_id, 'midi_' + x)


def setup_bundle(distdir):
    extend_env = (
        ('PATH', os.path.join(distdir, 'bin')),
        ('LD_LIBRARY_PATH', os.path.join(distdir, 'lib')),
    )
    for env_var, path in extend_env:
        if os.path.isdir(path):
            sys_path_str = os.getenv(env_var, None)
            sys_path = sys_path_str.split(os.pathsep) if sys_path_str else []
            if path not in sys_path:
                log('adding {} to {}'.format(path, env_var))
                sys_path.append(path)
                os.environ[env_var] = os.pathsep.join(sys_path)


def zenity_err(msg):
    steam_zenity = os.environ.get('STEAM_ZENITY', '/usr/bin/zenity')
    cmd = [steam_zenity, '--error', '--no-wrap', '--title=Boxtron Error']
    log_err(msg)
    if os.path.isfile(steam_zenity):
        subprocess.call(cmd + ['--text={}'.format(msg)])
    else:
        log_err('zenity ({}) is missing'.format(steam_zenity))


def run_dosbox(args):
    cmd = settings.get_dosbox_cmd()
    log('working dir: "{}"'.format(os.getcwd()))
    install_dir = toolbox.guess_game_install_dir()
    if install_dir:
        cmd = [x.replace('%install_dir%', install_dir) for x in cmd]
    else:
        log_warn('unrecognized installation directory')
    log(cmd + args)
    sys.stderr.flush()
    with toolbox.PidFile(fakescripteval.PID_FILE):
        try:
            subprocess.call(cmd + args)
        except FileNotFoundError as err:
            log_err(err)


def run_dosbox_with_conf(args):
    game_install_id = toolbox.get_game_install_id()
    confgen.cleanup_old_conf_files(game_install_id, args)
    name = confgen.uniq_conf_name(game_install_id, args)
    game_id = toolbox.get_game_global_id()
    tweaked_conf = tweaks.get_conf_tweak(game_id)
    static_conf = confgen.create_dosbox_configuration(args, tweaked_conf)
    if not static_conf:
        zenity_err("Game not recognized as DOSBox compatible.")
        sys.exit(1)
    if settings.get_confgen_force() or not os.path.isfile(name):
        log('saving', name, 'based on', args)
        confgen.create_user_conf_file(name, static_conf, args)
    setup_midi()
    auto_conf = confgen.create_auto_conf_file(static_conf)
    run_dosbox(['-conf', auto_conf, '-conf', name])


def run(cmd_line, wait=False):
    log('working dir: "{}"'.format(os.getcwd()))
    log('original command:', cmd_line)

    cmd_line = list(filter(lambda x: x != '^', cmd_line))

    if wait:
        fakescripteval.wait_for_previous_process()

    exe_path, exe = os.path.split(cmd_line[0]) if cmd_line else (None, '')

    if exe == 'iscriptevaluator.exe':
        status = fakescripteval.iscriptevaluator(cmd_line)
        sys.exit(status)

    # we don't want to detect hardware until we're sure we are starting
    # the actual game:
    settings.setup()

    chdir_tweak_needed, path = False, None
    try:
        chdir_tweak_needed, path = tweaks.check_cwd(cmd_line)
    except RuntimeError as err:
        zenity_err(err)
        sys.exit(2)

    if chdir_tweak_needed:
        if path:
            log_warn('game not found in', os.getcwd())
            log_warn('changing working dir to', path)
            os.chdir(path)
        else:
            log_err("can't figure out what to do with this command.")
            zenity_err("Error during detection of game installation.\nReport"
                       "this to: https://github.com/dreamer/boxtron/issues")
            sys.exit(2)

    game_id = toolbox.get_game_global_id()
    if tweaks.install_tweak_needed(game_id):
        tweaks.install(game_id)

    run_file(exe_path, exe, cmd_line)


def run_bat_file(bat):
    new_path, dosbox_args = toolbox.read_trivial_batch(bat)
    if new_path:
        os.chdir(new_path)
    run_dosbox_with_conf(dosbox_args)


def run_file(path, exe, cmd_line):

    game_id = toolbox.get_game_global_id()
    run_exe = os.environ.get('BOXTRON_RUN_EXE', None)

    if run_exe:
        # User wants to run different executable than the one
        # selected by Steam (e.g. sound setup).
        setup_midi()

        if toolbox.is_trivial_batch(run_exe):
            run_bat_file(run_exe)
        elif os.path.isfile(exe):
            run_dosbox_with_conf([run_exe, '-exit'])
        else:
            exe_path = os.path.join(os.getcwd(), run_exe)
            msg = 'File not found: ' + exe_path
            run_dosbox(['-conf', confgen.create_auto_conf_file({}),
                        '-c', '@echo ' + msg])  # yapf: disable

    elif tweaks.command_tweak_needed(game_id):
        # If AppId is included in known tweaks, then modify command line
        # before handing it over to .conf generator:
        log('tweaking command for app', game_id)
        tweaked_cmd = tweaks.tweak_command(game_id, cmd_line)
        if not tweaked_cmd:
            zenity_err('Game command line was not recognized.')
            sys.exit(1)
        run_dosbox_with_conf(tweaked_cmd)

    elif exe.lower() == 'dosbox.exe':
        # When dosbox with parameters is called, use them to
        # generate new .conf file.  When dosbox without parameters
        # is called, it implies: -conf dosbox.conf
        dosbox_args = cmd_line[1:] or ['-conf', 'dosbox.conf']
        run_dosbox_with_conf(dosbox_args)

    elif toolbox.is_trivial_batch(exe):
        # Publisher uploaded a .bat file to run dosbox
        run_bat_file(exe)

    elif os.path.isfile('dosbox.conf'):
        # Executable is unrecognised, but at least there's a dosbox.conf
        # let's pretend it was passed to dosbox.exe:
        run_dosbox_with_conf(['-conf', 'dosbox.conf'])

    elif exe.lower() == 'sierralauncher.exe':
        # A lot of games owned by Activision use Sierra Launcher
        # instead of running the DOSBox directly.
        ini_file = os.path.join(path, 'SierraLauncher.ini')
        if not os.path.isfile(ini_file):
            zenity_err('Sierra Launcher configuration file is missing.')
            sys.exit(1)
        log('parsing', ini_file)
        launcher = SierraLauncherConfig(ini_file=ini_file)
        log('launching', launcher.get_name())
        launcher.chdir()
        run_dosbox_with_conf(launcher.get_args())

    else:
        log('ignoring command:', cmd_line)
        zenity_err("Game not recognized as DOSBox compatible.")


def main():
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--get-native-path', action='store_true')
    group.add_argument('--get-compat-path', action='store_true')
    group.add_argument('--wait-before-run', action='store_true')
    group.add_argument('--version', action='store_true')
    args, run_cmd_line = parser.parse_known_args()

    setup_bundle(distdir=settings.distdir)

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(0)

    if args.version:
        print('Boxtron version', version.VERSION)
        sys.exit(0)

    if args.get_native_path:
        sys.exit(1)

    if args.get_compat_path:
        sys.exit(1)

    run(run_cmd_line, wait=args.wait_before_run)


if __name__ == "__main__":
    main()
