#!/usr/bin/python3
# The sound card's PipeWire profile, for exynos-callaudio, never saved (so a
# reboot or a PipeWire restart in the middle of a call comes back on the
# profile the user had):
#   exynos-callaudio-pw get        the active profile's name
#   exynos-callaudio-pw has NAME   exit 0 if the card offers NAME
#   exynos-callaudio-pw set NAME   switch to NAME, wait until it is active
# Runs as the session's user, against that user's PipeWire. The card is ALSA
# card $CARD, 0 if unset. Exit 1 on any failure, with the reason on stderr.
import json
import os
import subprocess
import sys
import time

CARD = int(os.environ.get('CARD', '0'))
WAIT = 3.0


def die(msg):
    print('exynos-callaudio-pw: %s' % msg, file=sys.stderr)
    sys.exit(1)


def device():
    try:
        out = subprocess.run(['pw-dump'], capture_output=True, text=True,
                             timeout=10).stdout
        objs = json.loads(out or '[]')
    except (OSError, subprocess.SubprocessError, ValueError) as e:
        die('pw-dump: %s' % e)
    for o in objs:
        if o.get('type') != 'PipeWire:Interface:Device':
            continue
        props = (o.get('info') or {}).get('props') or {}
        if props.get('device.api') == 'alsa' and props.get('api.alsa.card') == CARD:
            return o
    die('no PipeWire device for ALSA card %d' % CARD)


def params(dev, name):
    return ((dev.get('info') or {}).get('params') or {}).get(name) or []


def active(dev):
    p = params(dev, 'Profile')
    return p[0].get('name') if p else None


def index(dev, name):
    for p in params(dev, 'EnumProfile'):
        if p.get('name') == name and p.get('available') != 'no':
            return p.get('index')
    return None


def main(argv):
    if len(argv) == 2 and argv[1] == 'get':
        name = active(device())
        if name is None:
            die('no active profile')
        print(name)
        return 0
    if len(argv) == 3 and argv[1] == 'has':
        return 0 if index(device(), argv[2]) is not None else 1
    if len(argv) == 3 and argv[1] == 'set':
        dev = device()
        if active(dev) == argv[2]:
            return 0
        i = index(dev, argv[2])
        if i is None:
            die('no profile "%s"' % argv[2])
        r = subprocess.run(['pw-cli', 'set-param', str(dev['id']), 'Profile',
                            '{ "index": %d, "save": false }' % i],
                           stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
                           text=True, timeout=10)
        if r.returncode:
            die('pw-cli: %s' % r.stderr.strip())
        end = time.monotonic() + WAIT
        while time.monotonic() < end:
            if active(device()) == argv[2]:
                return 0
            time.sleep(0.1)
        die('profile "%s" not active after %.0f s' % (argv[2], WAIT))
    print('usage: exynos-callaudio-pw get | has NAME | set NAME', file=sys.stderr)
    return 2


if __name__ == '__main__':
    sys.exit(main(sys.argv))
