#!/usr/bin/python3
"""Root-owned narrow helper. Never accepts caller-supplied server or paths."""
import json, os, subprocess, sys
PROFILE='/opt/workdesk/remote-profile.json'
FIELDS={'server':'custom-rendezvous-server','relay':'relay-server','key':'key','api':'api-server'}
def run(*args):
    return subprocess.run(['/usr/bin/rustdesk',*args],capture_output=True,text=True,timeout=12,check=True).stdout.strip()
def main():
    if os.geteuid()!=0: raise RuntimeError('Administrator authentication is required for RustDesk system configuration.')
    if sys.argv[1:] not in [[],['--replace']]: raise RuntimeError('Unsupported configuration option.')
    with open(PROFILE) as f: profile=json.load(f)
    current={field:run('--option',name) for field,name in FIELDS.items()}
    conflict=any(current[k] and current[k]!=profile[k] for k in FIELDS)
    if conflict and '--replace' not in sys.argv:
        print(json.dumps({'conflict':True,'message':'RustDesk has another server configuration. Confirm replacement in Workdesk.'}));return
    for field,name in FIELDS.items(): run('--option',name,profile[field])
    # Attended access only. No password is read, exported or created.
    run('--option','approve-mode','click')
    actual={field:run('--option',name) for field,name in FIELDS.items()}
    if actual!= {k:profile[k] for k in FIELDS}: raise RuntimeError('RustDesk did not confirm the saved profile. Retry after its service starts.')
    os.makedirs('/var/lib/workdesk',mode=0o755,exist_ok=True)
    with open('/var/lib/workdesk/remote-profile.json.tmp','w') as f: json.dump(profile,f)
    os.chmod('/var/lib/workdesk/remote-profile.json.tmp',0o644)
    os.replace('/var/lib/workdesk/remote-profile.json.tmp','/var/lib/workdesk/remote-profile.json')
    print(json.dumps({'configured':True,'server':profile['server']}))
if __name__=='__main__':
    try: main()
    except Exception as e:
        print(json.dumps({'error':str(e)}));sys.exit(1)
