#!/usr/bin/env python3
"""Install verified ZIP downloads and a versioned NetWare mapping directory."""
import argparse, hashlib, json, pathlib, shutil, tempfile, zipfile
p=argparse.ArgumentParser()
p.add_argument('--config',default='/usr/local/etc/mars_nwe/nwserv.conf')
p.add_argument('--www',default='/usr/local/share/mars-vme/www')
p.add_argument('--packages',default=str(pathlib.Path(__file__).resolve().parent/'releases/windows'))
p.add_argument('--os', action='append', choices=['WIN95','WIN98','WINME','WINNT40','WIN2000','WINXP'])
a=p.parse_args();src=pathlib.Path(a.packages)
raw=(src/'manifest.json').read_bytes();manifest=json.loads(raw)
oses=('WIN95','WIN98','WINME','WINNT40','WIN2000','WINXP')
selected=tuple(x for x in oses if x in (a.os or oses))
if set(manifest)!=set(oses):raise SystemExit('Unexpected package manifest')
roots=[]
for line in pathlib.Path(a.config).read_text().splitlines():
 cols=line.split('#',1)[0].split()
 if len(cols)>=3 and cols[0]=='1' and cols[1].upper()=='SYS':roots.append(pathlib.Path(cols[2]))
if len(roots)!=1 or not roots[0].is_absolute() or not roots[0].is_dir():raise SystemExit('Exactly one existing absolute SYS volume required')
publics=[roots[0]/n for n in ('PUBLIC','public') if (roots[0]/n).is_dir()]
if len(publics)!=1:raise SystemExit('Exactly one existing PUBLIC directory required')
public=publics[0]
if public.is_symlink():raise SystemExit('PUBLIC must not be a symlink')
base=public/'DRIVERS'
if base.is_symlink():raise SystemExit('DRIVERS must not be a symlink')
base.mkdir(exist_ok=True,mode=0o755)
release=hashlib.sha256(raw+','.join(selected).encode()).hexdigest()[:12].upper();dest=base/release
# Validate every archive before changing web downloads.
with tempfile.TemporaryDirectory(prefix='.drivers-',dir=base) as tmp:
 stage=pathlib.Path(tmp)
 for os in selected:
  data=(src/(os+'.zip')).read_bytes()
  if hashlib.sha256(data).hexdigest()!=manifest[os]['sha256']:raise SystemExit('ZIP checksum mismatch: '+os)
  with zipfile.ZipFile(src/(os+'.zip')) as z:
   if len(z.namelist())!=len(set(z.namelist())):raise SystemExit('Duplicate ZIP members')
   expected={os+'/'+n for n in manifest[os]['files']}
   if set(z.namelist())!=expected:raise SystemExit('ZIP file list mismatch')
   for name in z.namelist():
    path=pathlib.PurePosixPath(name)
    if path.is_absolute() or '..' in path.parts or len(path.parts)!=2:raise SystemExit('Unsafe ZIP path')
    content=z.read(name)
    if hashlib.sha256(content).hexdigest()!=manifest[os]['files'][path.name]:raise SystemExit('File hash mismatch')
    target=stage/path;target.parent.mkdir(exist_ok=True);target.write_bytes(content);target.chmod(0o644)
 if dest.exists():
  for f in stage.rglob('*'):
   if f.is_file() and (dest/f.relative_to(stage)).read_bytes()!=f.read_bytes():raise SystemExit('Existing release differs; refusing overwrite')
 else:
  shutil.copytree(stage,dest)
  for d in [dest,*[x for x in dest.rglob('*') if x.is_dir()]]:d.chmod(0o755)
www=pathlib.Path(a.www)/'drivers'
if www.is_symlink():raise SystemExit('Web drivers directory must not be a symlink')
www.mkdir(parents=True,exist_ok=True)
backup=www/('previous-'+release)
for name in [*(os+'.zip' for os in oses),'manifest.json','SHA256SUMS']:
 target=www/name
 if target.is_symlink():raise SystemExit('Refusing symlink: '+str(target))
 if target.exists() and target.read_bytes()!=(src/name).read_bytes():
  backup.mkdir(exist_ok=True);shutil.copy2(target,backup/name)
 with tempfile.NamedTemporaryFile(dir=www,delete=False) as f:f.write((src/name).read_bytes());temp=pathlib.Path(f.name)
 temp.chmod(0o644);temp.replace(target)
(www/'enabled.json').write_text(json.dumps({'platforms':selected,'map':'MAP ROOT T:=SYS:PUBLIC/DRIVERS/'+release})+'\n')
(www/'enabled.json').chmod(0o644)
print('Web downloads installed: '+str(www))
print('MAP ROOT T:=SYS:PUBLIC/DRIVERS/'+release)
print('Grant NetWare read/file-scan rights only. Copy the OS directory locally before installation.')
