#!/usr/bin/python3 -I
"""DOS Installer: installs DOS games from disk images, CDs, archives or folders.

    plinius-dos-installer              the window
    plinius-dos-installer --play KEY   starts a DOS game in DOSBox (from its launcher)
    plinius-dos-installer --setup KEY  starts the game's own setup (from its page in the window)
    plinius-dos-installer --info ID    JSON about the game of a launcher in the app grid (its
                                       desktop id): {"title", "removal": "folder"|"files"|"list"}
    plinius-dos-installer --remove ID  removes that game as Remove in the window does (Settings'
                                       Apps page removes games with it)

--info and --remove exit 1 for a desktop id that is no game of the DOS Installer or ScummVM.
"""

import json
import os
import subprocess
import sys

sys.path.insert(0, "/usr/lib/plinius-dos-installer")

if len(sys.argv) == 3 and sys.argv[1] in ("--info", "--remove"):
    from dosinstall import dosgames, library
    game = dosgames.find_by_app_id(sys.argv[2], library.games())
    if not game:
        sys.exit(f"no such game: {sys.argv[2]}")
    if sys.argv[1] == "--info":
        print(json.dumps({"title": game.title, "removal": dosgames.removal(game)}, ensure_ascii=False))
        sys.exit(0)
    try:
        library.remove(game)
    except OSError as e:
        sys.exit(f"could not remove {game.title}: {e.strerror or e}")
    # The launchers of ScummVM's games follow scummvm.ini
    try:
        subprocess.run([os.environ.get("PLINIUS_SCUMMVM_LAUNCHERS", "plinius-scummvm-launchers")],
                       capture_output=True, timeout=60)
    except (OSError, subprocess.TimeoutExpired):
        pass
    sys.exit(0)

if len(sys.argv) == 3 and sys.argv[1] in ("--play", "--setup"):
    from dosinstall import dosgames, library
    game = dosgames.find_by_launcher(sys.argv[2], library.games())
    if not game:
        sys.exit(f"no such game: {sys.argv[2]}")
    sys.exit(dosgames.play(game, setup=sys.argv[1] == "--setup"))

from dosinstall.app import main  # noqa: E402

sys.exit(main())
