summaryrefslogtreecommitdiffstats
path: root/gamechestcli/gamechest/cliactions/run.py
blob: cf5ac4397c50cb7d072588863efc9c06fda6ba68 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import subprocess
import sys
from pathlib import Path

from ..gameconfig import config
from ..gamedb import GameDB
from ..statusdb import StatusDB


def run_game(game_db, profile_id, game_info):
    command = game_db.get_game_command(profile_id, game_info['id'])
    profile_dir = Path(config.get_profile_dir(profile_id))
    profile_game_dir = profile_dir / game_info['id']
    game_dir = config.get_games_install_basedir() / game_info['id']
    # note: glob('*/') globs regular files too, thus I filter on is_dir.
    game_dir = list(item
                    for item in game_dir.glob('*') if item.is_dir())[-1]
    game_dir = Path(game_dir)
    #tools_bin_path = config.get_games_saves_tools_bin_path()
    #new_env = dict(os.environ)
    #new_env['PATH'] = f'{tools_bin_path}:{new_env["PATH"]}'
    # path to mod/run scripts are already prepended by get_game_command, no
    # need to modify the path environment variable.
    profile_lockdir = profile_dir / '.lock'
    try:
        profile_lockdir.mkdir(parents=True, exist_ok=False)
    except FileExistsError:
        print('ERROR: profile is already locked, {profile_lockdir}',
              file=sys.stderr)
        sys.exit(1)
    try:
        subprocess.run(
            command,
            env={
                **os.environ,
                'PROFILE_DIR': str(profile_game_dir),
                'GAME_DIR': str(game_dir),
                'GAME_ID': game_info['id'],
            },
        )
    finally:
        profile_lockdir.rmdir()
        print('INFO: {profile_lockdir} removed')


def run(game_id, profile_id):
    game_db = GameDB()
    status_db = StatusDB()
    game_info = game_db.get_game_info(game_id)
    if not status_db.is_installed(game_info):
        # games is already installed
        print('Game', game_id, 'is not installed, aborting.', file=sys.stderr)
        return
    run_game(game_db, profile_id, game_info)


if __name__ == "__main__":
    run(*sys.argv[1:])