#!/usr/bin/python3
"""Narrow root installer: bind the packaged host to one existing local owner.

No identity, password, account secret or user file is read or generated as root.
The application subsequently creates/opens its profile under the owner UID.
"""
import argparse, grp, json, os, pwd, stat, subprocess, sys
from pathlib import Path

ROOT=Path('/etc/ruekran');BINDING=ROOT/'owner.conf';STATE=ROOT/'install-state.json'
DROPIN=Path('/etc/systemd/system/ruekran-host.service.d');UPGRADE=Path('/run/ruekran-install.state')
MARKER='# Managed by RuEkran\n'
def checked_file(path):
 info=path.lstat()
 if not stat.S_ISREG(info.st_mode) or info.st_uid!=0 or info.st_mode&0o022 or info.st_nlink!=1 or info.st_size>16384:raise RuntimeError('Unsafe service configuration')
 return path.read_text(encoding='utf-8')
def safe_directory(path):
 for part in reversed((path,*path.parents)):
  if not part.exists():part.mkdir(mode=0o755)
  info=part.lstat()
  if not stat.S_ISDIR(info.st_mode) or info.st_uid!=0 or info.st_mode&0o022:raise RuntimeError('Unsafe service configuration directory')
def write(path,text,mode=0o644):
 safe_directory(path.parent)
 if path.exists() or path.is_symlink():checked_file(path)
 temporary=path.with_name(path.name+'.new-'+str(os.getpid()))
 try:
  with temporary.open('x',encoding='utf-8',newline='\n') as stream:
   os.chmod(temporary,mode);stream.write(text);stream.flush();os.fsync(stream.fileno())
  os.replace(temporary,path)
 finally:
  if temporary.exists():temporary.unlink()
def read_binding():
 if not BINDING.exists() and not BINDING.is_symlink():return None
 data={}
 for line in checked_file(BINDING).splitlines():
  if not line or line.startswith('#'):continue
  key,separator,value=line.partition('=')
  if not separator or key in data or key not in ('owner_uid','profile','socket'):raise RuntimeError('Invalid service owner binding')
  data[key]=value
 if not data.get('owner_uid','').isdigit() or not data.get('profile','').startswith('/'):raise RuntimeError('Incomplete service owner binding')
 return data
def minimum_uid():
 try:
  path=Path('/etc/login.defs');info=path.lstat()
  if not stat.S_ISREG(info.st_mode) or info.st_uid!=0 or info.st_mode&0o022 or info.st_nlink!=1 or info.st_size>65536:return 1000
  values=[]
  for line in path.read_text(encoding='utf-8').splitlines():
   parts=line.split('#',1)[0].split()
   if parts and parts[0]=='UID_MIN':
    if len(parts)!=2 or not parts[1].isascii() or not parts[1].isdigit():return 1000
    values.append(int(parts[1]))
  return values[0] if len(values)==1 and 500<=values[0]<=60000 else 1000
 except (OSError,ValueError,UnicodeError):return 1000

def user(uid):
 entry=pwd.getpwuid(uid)
 if uid<minimum_uid() or uid>2147483647 or entry.pw_shell.endswith(('nologin','false')):raise RuntimeError('Choose a local desktop account')
 home=Path(entry.pw_dir)
 if not home.is_absolute() or home==Path('/') or not home.is_dir() or home.stat().st_uid!=uid:raise RuntimeError('The owner home is unavailable')
 return entry
def output(command):
 result=subprocess.run(command,capture_output=True,text=True,timeout=5)
 return result.stdout.strip() if result.returncode==0 else ''
def choose_owner():
 uid=os.environ.get('SUDO_UID','')
 if uid.isdigit() and int(uid)>=minimum_uid():
  try:return user(int(uid)).pw_uid
  except (KeyError,RuntimeError):pass
 active=output(['loginctl','show-seat','seat0','-p','ActiveSession','--value'])
 if active:
  uid=output(['loginctl','show-session',active,'-p','User','--value'])
  if uid.isdigit() and int(uid)>=minimum_uid():
   try:return user(int(uid)).pw_uid
   except (KeyError,RuntimeError):pass
 candidates=[]
 for entry in pwd.getpwall():
  try:
   if minimum_uid()<=entry.pw_uid<60000:user(entry.pw_uid);candidates.append(entry.pw_uid)
  except (KeyError,RuntimeError):pass
 return candidates[0] if len(candidates)==1 else None
def systemd_running():
 try:return Path('/proc/1/comm').read_text().strip()=='systemd'
 except OSError:return False
def configure(args):
 if os.geteuid()!=0:raise RuntimeError('Administrator authorization is required')
 previous=read_binding();uid=args.owner
 if uid is None:uid=int(previous['owner_uid']) if previous else choose_owner()
 if uid is None:
  print('РуЭкран установлен. Откройте программу в учётной записи владельца, чтобы настроить входящие подключения.');return 0
 entry=user(uid);requester=os.environ.get('PKEXEC_UID')
 if requester is not None and (not requester.isdigit() or int(requester)!=uid):raise RuntimeError('Only the requesting owner can configure the service')
 if previous and int(previous['owner_uid'])!=uid:raise RuntimeError('РуЭкран уже настроен для другой учётной записи. Обратитесь к администратору.')
 if args.stop:
  if not previous:raise RuntimeError('Фоновая служба ещё не настроена.')
  if systemd_running():subprocess.run(['systemctl','stop','ruekran-host.service','ruekran-capture.service'],check=True)
  print('Фоновая служба РуЭкран остановлена. ID и настройки сохранены.');return 0
 profile=previous['profile'] if previous else str(Path(entry.pw_dir)/'.local/state/ruekran')
 if not Path(profile).is_absolute() or str(Path(profile))!=os.path.normpath(profile) or any(c in profile for c in '\0\r\n') or len(profile.encode())>4096:raise RuntimeError('Invalid owner profile path')
 if not Path('/opt/ruekran/ruekran').is_file() or not Path('/opt/ruekran/ruekran-capture-broker').is_file():raise RuntimeError('Reinstall the complete RuEkran package')
 try:grp.getgrnam('render')
 except KeyError:subprocess.run(['/usr/sbin/groupadd','--system','render'],check=True)
 fresh=not STATE.exists()
 if not fresh:
  current=json.loads(checked_file(STATE))
  if current!={'schema':1,'configured':True}:raise RuntimeError('Invalid installer state')
 resume={}
 if UPGRADE.exists():
  for line in checked_file(UPGRADE).splitlines():
   key,separator,value=line.partition('=')
   if not separator or key not in ('host_active','broker_active','install_requested') or value not in ('0','1') or key in resume:raise RuntimeError('Invalid installer resume state')
   resume[key]=value=='1'
 write(BINDING,MARKER+'owner_uid='+str(uid)+'\nprofile='+profile+'\nsocket=/run/ruekran-owner/host.sock\n')
 write(ROOT/'capture.conf',MARKER+'owner_uid='+str(uid)+'\nsocket=/run/ruekran-capture/capture.sock\nclient_executable=/opt/ruekran/ruekran\n')
 # JSON quoting is also valid for these restricted systemd string values;
 # double literal percent signs to prevent systemd specifier expansion.
 home=json.dumps('HOME='+entry.pw_dir.replace('%','%%'),ensure_ascii=False)
 write(DROPIN/'owner.conf',MARKER+'[Service]\nUser='+str(uid)+'\nEnvironment='+home+'\nEnvironment=XDG_RUNTIME_DIR=/run/user/'+str(uid)+'\nEnvironment=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/'+str(uid)+'/bus\n')
 write(STATE,json.dumps({'schema':1,'configured':True})+'\n')
 if systemd_running():
  subprocess.run(['systemctl','daemon-reload'],check=True)
  if fresh or resume.get('install_requested',False) or args.start:subprocess.run(['systemctl','enable','ruekran-capture.service','ruekran-host.service'],check=True)
  if fresh or resume.get('install_requested',False) or resume.get('host_active',False) or args.start:subprocess.run(['systemctl','start','ruekran-host.service'],check=True)
  elif resume.get('broker_active',False):subprocess.run(['systemctl','start','ruekran-capture.service'],check=True)
 if UPGRADE.exists():UPGRADE.unlink()
 print('Фоновая служба РуЭкран настроена. Сохранённые ID и настройки не менялись.');return 0
def main():
 parser=argparse.ArgumentParser();parser.add_argument('--owner',type=int);parser.add_argument('--auto-owner',action='store_true');action=parser.add_mutually_exclusive_group();action.add_argument('--start',action='store_true');action.add_argument('--stop',action='store_true');args=parser.parse_args()
 try:return configure(args)
 except (OSError,ValueError,KeyError,RuntimeError,subprocess.SubprocessError) as error:
  print('Не удалось настроить службу РуЭкран: '+str(error),file=sys.stderr);return 1
if __name__=='__main__':sys.exit(main())
