#!/usr/bin/env python3
# summary: Lock this session and show the sign-in screen.
"""Keep this session locked and show the sign-in screen. Usage: starchaser switch user"""
import subprocess
import sys
import time
from pathlib import Path


def main(args):
    if args in (['-h'],['--help']): print(__doc__);return 0
    if args: return 2
    try:
        subprocess.run(['starchaser', 'lock'],check=True,timeout=25)
        for _ in range(25):
            result=subprocess.run(['qs','-p',str(Path.home()/'.config/quickshell/lock'),'ipc','call','--','lock','locked'],capture_output=True,text=True,timeout=3)
            if result.returncode==0 and result.stdout.strip()=='true': break
            time.sleep(.2)
        else: raise RuntimeError("The lock screen didn't confirm it is secure.")
        subprocess.run(['pkexec','/usr/local/lib/starchaser/starchaser-switch-session','open'],check=True,timeout=45)
    except (OSError,RuntimeError,subprocess.SubprocessError) as error:
        subprocess.run([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'],'starchaser', 'notify','-a','Starchaser',"Couldn't switch user",'Your session stays locked. Unlock and try again.'],check=False)
        print(str(error),file=sys.stderr);return 1
    return 0


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