#!/usr/bin/env python3
"""Switch between locked local sessions without ending anyone's apps.
Usage: starchaser-switch-session list | open | return SESSION
open is called through polkit by a locked local account; return is greeter-only through sudo.
"""
import fcntl
import json
import os
import re
import subprocess
import sys
import tomllib
from pathlib import Path
RUNTIME=Path('/run/starchaser-switch')
CONFIG=Path('/etc/greetd/config.toml')


def command(*args):
    r=subprocess.run(args,capture_output=True,text=True,timeout=30)
    if r.returncode: raise RuntimeError("Couldn't show the sign-in screen. Your session is still locked.")
    return r.stdout.strip()


def sessions():
    result=[]
    for line in command('loginctl','list-sessions','--no-legend','--no-pager').splitlines():
        ident=line.split()[0]
        if not re.fullmatch(r'[a-zA-Z0-9_-]+',ident): continue
        values=command('loginctl','show-session',ident,'--no-pager',
            '-p','User','-p','Name','-p','Seat','-p','Class','-p','Type','-p','VTNr','-p','Active','-p','LockedHint','-p','Remote')
        row=dict(part.split('=',1) for part in values.splitlines() if '=' in part)
        if row.get('Seat')=='seat0' and row.get('Remote')=='no': result.append(dict(row,id=ident))
    return result


def open_greeter(uid):
    current=sessions()
    if not any(s.get('User')==str(uid) and s.get('Active')=='yes' and s.get('LockedHint')=='yes' and s.get('Class')=='user' for s in current):
        raise ValueError('Lock this local session before switching users.')
    for row in current:
        if row.get('Class')=='greeter':
            command('loginctl','activate',row['id']); return
    occupied={int(s.get('VTNr','0')) for s in current if s.get('VTNr','0').isdigit()}
    for vt in range(8,13):
        if vt in occupied: continue
        template=tomllib.loads(CONFIG.read_text())['default_session']
        # Root-owned input only. Never copy automatic sign-in into a switching greeter.
        RUNTIME.mkdir(mode=0o755,parents=True,exist_ok=True)
        text=f'[terminal]\nvt = {vt}\nswitch = true\n[general]\nrunfile = "/run/starchaser-switch/{vt}.run"\n[default_session]\n'
        text+='command = '+json.dumps(template['command'])+'\nuser = "greeter"\n'
        if 'service' in template: text+='service = '+json.dumps(template['service'])+'\n'
        (RUNTIME/f'{vt}.toml').write_text(text)
        command('systemctl','start',f'starchaser-switch@{vt}.service'); return
    raise ValueError('All sign-in screens are in use. Return to a signed-in account or sign out of one first.')


def return_to(ident):
    if not re.fullmatch(r'[a-zA-Z0-9_-]+',ident): raise ValueError('Invalid session.')
    current=sessions()
    if not any(s.get('Class')=='greeter' and s.get('Active')=='yes' for s in current):
        raise ValueError('Return from the sign-in screen only.')
    if not any(s['id']==ident and s.get('Class')=='user' and s.get('Type') in ('wayland','x11') and s.get('LockedHint')=='yes' for s in current):
        raise ValueError('That locked session is no longer available.')
    command('loginctl','activate',ident)
    # This temporary sign-in screen has finished its job. Stop it after activating
    # the locked desktop so the next switch starts fresh, and no paused greeter
    # retains a busy return dialog. Never stop the main sign-in service.
    greeter=next(s for s in current if s.get('Class')=='greeter' and s.get('Active')=='yes')
    vt=greeter.get('VTNr','')
    if vt in {str(n) for n in range(8,13)} and (RUNTIME/f'{vt}.toml').is_file():
        command('systemctl','stop','--no-block',f'starchaser-switch@{vt}.service')


def main(args):
    if args in (['--help'],['-h']): print(__doc__);return
    if args==['list']:
        print(json.dumps({s['Name']:s['id'] for s in sessions() if s.get('Class')=='user' and s.get('Type') in ('wayland','x11') and s.get('LockedHint')=='yes'}));return
    if os.geteuid()!=0: raise ValueError('This action must go through the sign-in service.')
    if args==['open']:
        uid=int(os.environ.get('PKEXEC_UID','-1'))
        if uid<1000: raise ValueError('A local account must request this action.')
        RUNTIME.mkdir(mode=0o755,parents=True,exist_ok=True)
        with (RUNTIME/'switch.lock').open('a') as lock:
            fcntl.flock(lock,fcntl.LOCK_EX);open_greeter(uid)
    elif len(args)==2 and args[0]=='return' and os.environ.get('SUDO_USER')=='greeter':
        return_to(args[1])
    else: raise ValueError('Use list, open, or return SESSION from the sign-in screen.')


if __name__=='__main__':
    try: main(sys.argv[1:])
    except (OSError,ValueError,RuntimeError,subprocess.SubprocessError) as e: print(str(e),file=sys.stderr);sys.exit(1)
