#!/usr/bin/python3
"""Fixed, OS-authorized Linux client installer. No renderer-provided commands."""
import argparse
import fcntl
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import pwd
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import time

sys.dont_write_bytecode=True

BASE=Path('/usr/lib/keelark-access')
PROFILES=Path('/etc/keelmesh-vpn')
UNITS=Path('/etc/systemd/system')
NAME=re.compile(r'^[a-z][a-z0-9-]{0,31}$')

def protected(path):
 for p in [path,*path.parents]:
  s=p.lstat()
  if p.is_symlink() or s.st_uid!=0 or s.st_mode&0o022:raise ValueError('installation paths must be root protected')

def owner():
 if os.geteuid()!=0:raise ValueError('system authorization is required')
 uid=os.environ.get('PKEXEC_UID') or os.environ.get('SUDO_UID')
 if not uid or not uid.isdigit() or int(uid)==0:raise ValueError('run from the owning user with sudo or the system authorization prompt')
 return pwd.getpwuid(int(uid))

def private_path(path,user,directory=False):
 home=Path(user.pw_dir)
 if not path.is_absolute() or '..' in path.parts or path==home or home not in path.parents:raise ValueError('state must be inside the owning user home')
 for p in [path,*path.parents]:
  if p==home.parent:break
  s=p.lstat()
  if p.is_symlink() or s.st_uid!=user.pw_uid or s.st_mode&0o022:raise ValueError('private state path owner or permissions are unsafe')
 s=path.lstat()
 if s.st_mode&0o077 or (directory and not path.is_dir()) or (not directory and not path.is_file()):raise ValueError('client state must be private')

def no_duplicates(pairs):
 d={}
 for k,v in pairs:
  if k in d:raise ValueError('duplicate configuration field')
  d[k]=v
 return d

def read_private(path,user,limit):
 private_path(path,user)
 with path.open('rb') as f:b=f.read(limit+1)
 if len(b)>limit:raise ValueError('client input exceeds limit')
 return b

def component_files():
 protected(BASE)
 protected(BASE/'components.json')
 m=json.loads((BASE/'components.json').read_text())
 expected={'keelmesh-core','install-deepvpn.py','install-client-helper'}
 if set(m['files'])!=expected:raise ValueError('invalid component inventory')
 for name,digest in m['files'].items():
  p=BASE/name;protected(p)
  if not p.is_file() or hashlib.sha256(p.read_bytes()).hexdigest()!=digest:raise ValueError('installed component integrity mismatch')
 return m

def invoke(*args,check=True):
 return subprocess.run([str(a) for a in args],check=check,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,timeout=60)

def install(profile,config,pin,user):
 component_files()
 if (not NAME.fullmatch(profile) or config.name!='runtime.json' or pin.name!='server.cbor' or config.parent!=pin.parent or config.parent.name!=profile):raise ValueError('invalid fixed enrollment paths')
 b=read_private(config,user,64<<10);peer=read_private(pin,user,16<<10);c=json.loads(b,object_pairs_hook=no_duplicates)
 if c.get('version')!=3 or c.get('mode')!='client' or c.get('authorization')!='owner-pinned' or not c.get('network_access') or c.get('key_store')!='file' or c.get('run_uid')!=user.pw_uid or c.get('run_gid')!=user.pw_gid or c.get('session_seconds')!=600:raise ValueError('client ownership or signed permission requirements not met')
 state=Path(c['state_dir']);private_path(state,user,True)
 if not re.fullmatch(r'/[A-Za-z0-9_./-]+',str(state)):raise ValueError('state path contains unsupported characters')
 if c.get('peer_bundle')!=str(pin):raise ValueError('peer bundle path differs from enrollment')
 label='keelmesh-vpn-'+profile+'.service'
 if (PROFILES/(profile+'.json')).exists() or (UNITS/label).exists():raise ValueError('profile already installed; existing identity and service retained')
 # Stage a bounded immutable input copy before the root installer sees it.
 parent=Path('/var/lib/keelark-access');parent.mkdir(mode=0o700,exist_ok=True);protected(parent)
 with tempfile.TemporaryDirectory(prefix='install-',dir=str(parent)) as td:
  stage=Path(td);stage.chmod(0o700);newpin=stage/'server.cbor';newpin.write_bytes(peer);newpin.chmod(0o600)
  c['peer_bundle']=str(newpin);newconfig=stage/'runtime.json';newconfig.write_text(json.dumps(c));newconfig.chmod(0o600)
  invoke(BASE/'keelmesh-core','verify-runtime','--path',newconfig)
  spec=importlib.util.spec_from_file_location('keelark_network_installer',BASE/'install-deepvpn.py');module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
  args=argparse.Namespace(profile=profile,binary=str(BASE/'keelmesh-core'),expected_sha256=hashlib.sha256((BASE/'keelmesh-core').read_bytes()).hexdigest(),config=str(newconfig),peer_bundle=str(newpin),auto_up=True,profile_binary=True,profiles_dir=None,shared_gateway=None,fail_closed_on_error=False)
  module.install(args)
 print(json.dumps({'installed':profile,'identity_preserved':True,'automatic_permissions_granted':False}))

def remove(profile,user):
 if not NAME.fullmatch(profile):raise ValueError('invalid profile')
 config=PROFILES/(profile+'.json');pin=PROFILES/(profile+'-peer.cbor');unit=UNITS/('keelmesh-vpn-'+profile+'.service');label=unit.name
 for p in [config,pin,unit]:protected(p)
 b=config.read_bytes();c=json.loads(b)
 binary='/opt/keelmesh-vpn/profiles/'+profile+'/deepvpn'
 expected='ExecStart='+binary+' manager --config '+str(config)+' --socket /run/keelmesh-vpn/'+profile+'.sock'
 if c.get('mode')!='client' or c.get('run_uid')!=user.pw_uid or c.get('authorization')!='owner-pinned' or not ({expected,expected+' --auto-up'} & set(unit.read_text().splitlines())):raise ValueError('installed client ownership or service differs')
 images={p:p.read_bytes() for p in [config,pin,unit]};was_active=invoke('/usr/bin/systemctl','is-active','--quiet',label,check=False).returncode==0
 archive=PROFILES/'Retired';archive.mkdir(mode=0o700,exist_ok=True);protected(archive);dest=archive/(profile+'-'+str(time.time_ns()));dest.mkdir(mode=0o700)
 for p,data in images.items():q=dest/p.name;q.write_bytes(data);q.chmod(0o600)
 try:
  invoke('/usr/bin/systemctl','stop',label)
  if invoke('/usr/bin/systemctl','is-active','--quiet',label,check=False).returncode==0:raise RuntimeError('service remains active; files retained')
  for p,data in images.items():
   if p.read_bytes()!=data:raise ValueError('installation changed during retirement')
  invoke('/usr/bin/systemctl','disable',label)
  for p in images:p.unlink()
  invoke('/usr/bin/systemctl','daemon-reload')
 except BaseException:
  for p,data in images.items():
   if not p.exists():p.write_bytes(data);p.chmod(0o644 if p==unit else 0o600)
  invoke('/usr/bin/systemctl','daemon-reload',check=False)
  if was_active:invoke('/usr/bin/systemctl','enable','--now',label,check=False)
  raise
 print(json.dumps({'removed':profile,'identity_preserved':True,'recovery_directory':str(dest),'other_profiles_untouched':True}))

def main():
 p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=['install','remove']);p.add_argument('profile');p.add_argument('--config',type=Path);p.add_argument('--pin',type=Path);a=p.parse_args();u=owner()
 if not NAME.fullmatch(a.profile):raise ValueError('invalid profile')
 lockdir=Path('/run/keelark-access');lockdir.mkdir(mode=0o755,exist_ok=True);protected(lockdir)
 fd=os.open(lockdir/(a.profile+'.install.lock'),os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600)
 try:
  fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
  if a.action=='remove':
   if a.config or a.pin:raise ValueError('remove accepts only a profile')
   remove(a.profile,u)
  else:
   base=Path(u.pw_dir)/'.config/KeelmeshVPN/enrollment'/a.profile
   install(a.profile,a.config or base/'runtime.json',a.pin or base/'server.cbor',u)
 finally:os.close(fd)
if __name__=='__main__':
 try:main()
 except Exception as e:sys.exit('Keelark Access: '+str(e))
