#!/usr/bin/python3
# SPDX-License-Identifier: MIT
"""Launch a user-owned Pianoteq session without changing volume or presets."""
import os
import pathlib
import sys

def main():
    if os.geteuid() == 0:
        raise RuntimeError('Run the player as its ordinary user, not root')
    target = pathlib.Path(os.environ.get('PIANORT_EXECUTABLE', '/opt/pianoteq/current/Pianoteq')).resolve(strict=True)
    if not target.is_file() or not os.access(target, os.X_OK):
        raise RuntimeError('Configured Pianoteq executable is not executable')
    mode = os.environ.get('PIANORT_MULTICORE', 'max')
    if mode != 'max':
        raise RuntimeError('This initial profile supports PIANORT_MULTICORE=max only')
    for entry in pathlib.Path('/proc').iterdir():
        if not entry.name.isdigit():
            continue
        try:
            if entry.stat().st_uid == os.getuid() and pathlib.Path(os.readlink(entry / 'exe')) == target:
                raise RuntimeError('Pianoteq is already running; close it before starting the service')
        except (FileNotFoundError, PermissionError, ProcessLookupError):
            continue
    env = os.environ.copy()
    library = '/usr/lib/pianort/mlockall.so'
    if not pathlib.Path(library).is_file():
        raise RuntimeError('PianoRT memory-lock helper is missing')
    env['LD_PRELOAD'] = library + (' ' + env['LD_PRELOAD'] if env.get('LD_PRELOAD') else '')
    os.execve('/usr/bin/pw-jack', ['pw-jack', str(target), '--multicore', 'max'], env)

if __name__ == '__main__':
    try:
        main()
    except (OSError, RuntimeError) as error:
        print('PianoRT: ' + str(error), file=sys.stderr)
        raise SystemExit(1)
