#!/usr/bin/env python3
"""SCDO T460p/first-generation Linux amd64 upgrade, release 1.0.1.
Default: read-only preflight. --apply: backup, install/upgrade, enable and start.
No database removal, GPU/CUDA setup, wallet import, or automatic binary updates.
"""
import argparse, concurrent.futures, fcntl, hashlib, importlib.util, json, os
from pathlib import Path, PurePosixPath
import platform, pwd, re, shlex, shutil, socket, stat, subprocess, sys, tarfile, tempfile, time, urllib.request
VERSION='1.0.1'
BASE='https://scdo.com.au/downloads/'
ARTIFACTS={
 'shard0':('shard0-5680/scdo-shard0-5680-58c2f3e-r2.tar.gz','dffd23b703d54fbea04acb85b51f4b3c929234a6bee9281b8b2a00c9266a4f42',34437489),
 'classic':('classic-upgrade/scdo-classic-node-9a6ee41.tar.gz','a9e029be4c50f6014676193a619db7387515b4782f4c986c32f6e339f67b02cb',10704554),
 'templates':('node/scdo-node-linux-amd64.tar.gz','f17fdb3500409276d34f330e25215343f56bd3c97f948d7a4448be1ef52dc957',10230782),
 'agent':('wallet/linux/scdo-agent_0.5.11_linux_amd64.tar.gz','91287100b4c9837736944777728ee46855f392939fccf6bfebc84f13db764ef6',7452450),
 'agent-install':('ledger/0.5.11-customer/install.py','ccb55949d1d4c83428a933e4ce479d210f4c3f791c11ac2bdb4b48985d9db960',18803),
 'agent-manifest':('ledger/0.5.11-customer/manifest.json','d4e93c38dffe222e14e5848c3da261e82ec23e7d1699a3b57090b25324396b31',916)}
GETH_SHA='6600dcd9511c3b216b1737c3364082d80df5350263c80bc255808faf65a91a8a'
NODE_SHA='1021475607139de506f180c133c5e62da66452235d6336fe85fd906568ed2bb6'
AGENT_SHA='83bbbba4ffabe409c16d912ea24515f9a0f42657edab1bdc84df2b7c7532b42f'
GENESIS_SHA='0d5350224e4068f4c9f89ce07fcdd73ec3d8ede4857bd2056c51e01fa7468d12'
GENESIS_HASH='0xbbb083f7cf5d176ab603f7e47b082305a579d3a4c198883bb7541f29a970cb12'
BOOT='enode://62350e72ce3c1f208f6435e4512ea9dbeefec2c303f01f47a939501afcf6b8d228e1aef4c9a9566026bb4cc7c75a15dbf87099db4bfcc1acbde12de4a10e7d92@67.219.105.146:30368'
MEL=['67.219.111.197:8027','139.84.199.96:8028','67.219.109.174:8029','67.219.105.53:8026']
ROOT=Path('/')
class Refusal(Exception): pass
def need(ok,msg):
 if not ok: raise Refusal(msg)
def rp(path): return ROOT/str(path).lstrip('/')
def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for b in iter(lambda:f.read(1024*1024),b''): h.update(b)
 return h.hexdigest()
def safe(p):
 p=Path(p); need(p.is_absolute() and '..' not in p.parts,'Unsafe noncanonical path')
 for a in [p]+list(p.parents):
  need(not a.is_symlink(),'Symlink path refused: '+str(a))
 return p
def run(args,check=True,timeout=60):
 r=subprocess.run(args,stdin=subprocess.DEVNULL,capture_output=True,text=True,timeout=timeout)
 if check: need(r.returncode==0,'Command failed: '+Path(args[0]).name+' (output withheld; inspect locally)')
 return r

def unit_info(name):
 if ROOT!=Path('/'):
  f=rp('/systemd-fixture.json'); return json.loads(f.read_text()).get(name,{}) if f.exists() else {}
 r=run(['systemctl','show',name,'-p','LoadState','-p','FragmentPath','-p','ExecStart','-p','User','-p','MainPID','-p','ActiveState','-p','UnitFileState'],False)
 j=dict(l.split('=',1) for l in r.stdout.splitlines() if '=' in l)
 return j if j.get('LoadState')=='loaded' else {}
def argv(j):
 m=re.search(r'argv\[\]=(.*?) ; ignore_errors=',j.get('ExecStart',''))
 need(m is not None,'Unsupported systemd launch format; no changes')
 a=shlex.split(m.group(1));need(all(v=='' or re.fullmatch(r'[A-Za-z0-9_./,:=@+-]+',v) for v in a),'Complex service command requires local review')
 return a
def config_arg(a):
 need('-c' in a and a.index('-c')+1<len(a),'Missing Classic config argument')
 p=Path(a[a.index('-c')+1]);need(p.is_absolute(),'Relative Classic config requires local review')
 return safe(rp(p))
def probe_ports(ports,owners):
 # Inspect every binding, not just MainPID: accept only the expected unit cgroup.
 if ROOT!=Path('/'): return
 for port in sorted(set(ports)):
  r=run(['ss','-H','-lntup','sport = :'+str(port)],False);need(r.returncode==0,'Port ownership inspection failed');out=r.stdout
  for line in out.splitlines():
   pids=re.findall(r'pid=(\d+)',line);need(pids,'Occupied port '+str(port)+' has unknown owner')
   for pid in pids:
    cg=Path('/proc/'+pid+'/cgroup').read_text()
    need(any('/'+n in cg and (('/'+n+'\n') in cg or ('/'+n+'/') in cg) for n in owners),'Port '+str(port)+' belongs to another process; nothing killed')
def plan():
 need(sys.platform=='linux' and platform.machine() in ('x86_64','amd64'),'Linux amd64 required')
 classic=[unit_info('node'+str(i)+'.service') for i in range(1,5)]
 ours=[unit_info('scdo-t460p-classic'+str(i)+'.service') for i in range(1,5)]
 need(not (any(classic) and any(ours)),'Mixed Classic service layouts require review')
 infos=classic if any(classic) else ours
 existing=any(infos);need(not existing or all(infos),'Partial Classic service set: no changes')
 units=[];back=[];nodebin=None
 if existing:
  binaries=set()
  for i,j in enumerate(infos,1):
   a=argv(j);need(Path(a[0]).name in ('node','scdo-node') and 'start' in a,'Unknown node launch')
   need(j.get('User') not in ('','root'),'Root-run Classic service requires local review')
   need('-m' in a and a.index('-m')+1<len(a) and a[a.index('-m')+1] in ('stop','start'),'Explicit known Classic mining mode required')
   if a[a.index('-m')+1]=='start':need(j.get('ActiveState')=='active','Disabled/stopped mining-mode node will not be auto-started')
   p=config_arg(a);cfg=json.loads(p.read_text());need(cfg.get('genesis',{}).get('shard')==i,'Classic config shard mismatch')
   need(cfg.get('basic',{}).get('dataDir'),'Classic dataDir missing')
   binaries.add(a[0]);back.extend([str(p),j.get('FragmentPath','')])
   # Existing configuration, data directory, P2P identity and miner flags are kept.
   units.append(('node' if any(classic) else 'scdo-t460p-classic')+str(i)+'.service')
  need(len(binaries)==1,'Classic units do not share one binary; local review required')
  nodebin=str(safe(rp(binaries.pop())));need(Path(nodebin).is_file(),'Existing node binary missing')
  back.append(nodebin)
 else:
  need(not rp('/etc/scdo-t460p').exists(),'Unmapped existing T460p configuration: do not overwrite local identities')
  units=['scdo-t460p-classic'+str(i)+'.service' for i in range(1,5)]
  # Never quietly start a second set beside an unrecognized legacy chain.
  homes=[rp('/home/scdo'),rp('/root'),rp('/var/lib/scdo-t460p/home')]
  for home in homes:
   db=home/'.scdo'
   need(not db.exists() or not any(db.iterdir()),'Existing chain data without recognized units; manual mapping required')
  nodebin=str(rp('/opt/scdo-t460p/1.0.1/node'))
 shard_names=['scdo-shard0-node.service','scdo-evm-shard0.service','scdo-shard0-5680.service','scdo-t460p-shard0.service']
 shard=[(n,unit_info(n)) for n in shard_names];shard=[(n,j) for n,j in shard if j]
 need(len(shard)<=1,'Multiple Shard0 units require local review')
 if shard:
  n,j=shard[0];a=argv(j);need(Path(a[0]).name=='geth' and '--datadir' in a,'Unknown Shard0 command')
  need('--networkid' in a and a[a.index('--networkid')+1]=='5680','Existing Shard0 is not network 5680')
  need(not any(v in a for v in ['--mine','--unlock','--password']),'Mining/unlocking Shard0 unit requires local review')
  data=a[a.index('--datadir')+1];safe(rp(data));geth=str(safe(rp(a[0])))
  need(Path(geth).is_file(),'Existing Shard0 binary missing')
  need(sha(geth)==GETH_SHA,'Unknown existing Shard0 binary: genesis compatibility must be reviewed')
  back.extend([geth,j.get('FragmentPath','')]);sunit=n
  # Preserve working data/bootstraps and all existing arguments. Only official checkpoint URL changes.
  if '--scdo.checkpoint.url' in a:a[a.index('--scdo.checkpoint.url')+1]='https://scdo.com.au/checkpoint/shard0/latest.json'
  else:a+=['--scdo.checkpoint.url','https://scdo.com.au/checkpoint/shard0/latest.json']
  sargs=a
 else:
  data='/var/lib/scdo-t460p/shard0';geth=str(rp('/opt/scdo-t460p/1.0.1/geth'));sunit='scdo-t460p-shard0.service';sargs=[]
  need(not rp(data).exists(),'Unmapped existing Shard0 data: no overwrite or reinitialization')
 units.append(sunit)
 owners=units
 # Standard Classic ports plus fresh layout ports; no port stealing or batch kill.
 probe_ports([30368,18545,18551,8026,8027,8028,8029,8036,8037,8038,8039,8046,8047,8048,8049,8056,8057,8058,8059],owners)
 for p in back:
  if p:safe(p)
 return {'classic_existing':existing,'classic_units':units[:4],'nodebin':nodebin,'shard0_existing':bool(shard),'shard0_unit':sunit,'geth':geth,'data':data,'shard0_args':sargs,'backup':list(dict.fromkeys(p for p in back if p)),'units':units}

def fetch(k,dest):
 path,pin,size=ARTIFACTS[k];u=BASE+path
 with urllib.request.urlopen(u,timeout=60) as r,open(dest,'xb') as out:
  need(r.status==200 and r.url.startswith(BASE),'Official HTTPS artifact URL required')
  h=hashlib.sha256();n=0
  while True:
   b=r.read(1024*1024)
   if not b:break
   n+=len(b);need(n<=size,'Artifact exceeds pinned size');h.update(b);out.write(b)
 need(n==size and h.hexdigest()==pin,'Artifact size/hash mismatch: '+k)
 return dest

def extract_member(archive,name,dest,pin=None,mode=0o600):
 with tarfile.open(archive,'r:gz') as t:
  ms=t.getmembers();need(len(ms)<1000,'Archive member limit')
  seen=set()
  for m in ms:
   pp=PurePosixPath(m.name);need(not pp.is_absolute() and '..' not in pp.parts and m.name not in seen and (m.isfile() or m.isdir()),'Unsafe archive member');seen.add(m.name)
  m=t.getmember(name);need(m.isfile() and m.size<=100*1024*1024,'Invalid payload member')
  with t.extractfile(m) as src,open(dest,'xb') as out:shutil.copyfileobj(src,out)
 os.chmod(dest,mode)
 if pin:need(sha(dest)==pin,'Inner binary hash mismatch')
 return dest

def prepare(work):
 fs={k:fetch(k,work/(k+'.download')) for k in ARTIFACTS}
 extract_member(fs['shard0'],'scdo-shard0-5680-bundle/geth',work/'geth',GETH_SHA,0o755)
 extract_member(fs['shard0'],'scdo-shard0-5680-bundle/genesis.json',work/'genesis.json',GENESIS_SHA)
 extract_member(fs['classic'],'scdo-classic-node-9a6ee41/node',work/'node',NODE_SHA,0o755)
 extract_member(fs['templates'],'scdo-node-linux-amd64/scdo-client',work/'client',mode=0o755)
 extract_member(fs['agent'],'scdo-agent',work/'scdo-agent',AGENT_SHA,0o755)
 shutil.copy2(fs['agent-install'],work/'agent-install.py');shutil.copy2(fs['agent-manifest'],work/'manifest.json')
 (work/'payload').mkdir();shutil.copy2(work/'scdo-agent',work/'payload/scdo-agent')
 for i in range(1,5):extract_member(fs['templates'],'scdo-node-linux-amd64/config/node-shard'+str(i)+'.json',work/('template'+str(i)+'.json'))
 need('0.5.11' in run([str(work/'scdo-agent'),'version']).stdout,'Agent version mismatch')
 v=run([str(work/'geth'),'version']).stdout;need('58c2f3e' in v,'Shard0 commit mismatch')
 need(b'Scdo_V2.0.0' in (work/'node').read_bytes(),'Classic version marker missing')
 print('All public artifact sizes, SHA256 and inner binaries verified. No services changed.')
 return fs

def agent_preflight(work):
 spec=importlib.util.spec_from_file_location('pinned_ledger',work/'agent-install.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
 state=rp('/var/lib/scdoagent/.scdo-agent/installer-state.json')
 if state.exists(): name=json.loads(state.read_text()).get('name','')
 else:
  hostname=re.sub('[^A-Za-z0-9_-]','-',socket.gethostname())[:30]
  mid=rp('/etc/machine-id').read_text().strip() if rp('/etc/machine-id').exists() else hostname
  name='t460p-'+hostname+'-'+hashlib.sha256(mid.encode()).hexdigest()[:8]
 need(m.valid_name(name),'Invalid existing agent instance name')
 host=m.Host(str(ROOT));need(not m.preflight(host,name),'Ledger preflight refused; nothing upgraded')
 if ROOT==Path('/'):
  out=run(['systemctl','list-units','--all','--no-legend','--plain','scdo-host-agent@*.service','scdo-agent@*.service'],False).stdout
  for line in out.splitlines():
   names=re.findall(r'(scdo-(?:host-)?agent@[^ ]+\.service)',line)
   for unit in names:need(unit=='scdo-host-agent@'+name+'.service','An existing Ledger/bot identity is not mapped; no duplicate enrollment')
  dest=rp('/var/lib/scdoagent/.scdo-agent/bin/scdo-agent')
  need(not dest.exists() or sha(dest)==AGENT_SHA,'Existing agent binary differs; preserve and review before upgrade')
 drop=rp('/etc/systemd/system')/('scdo-host-agent@'+name+'.service.d')/'90-t460p-ledger.conf'
 need(not drop.exists() or drop.read_bytes()==ledger_dropin(name),'Unknown Ledger instance drop-in: local review required')
 return m,host,name

def ledger_dropin(name):
 return ('[Service]\nExecStart=\nExecStart=/var/lib/scdoagent/.scdo-agent/bin/scdo-agent --lang en --data-dir /var/lib/scdoagent/.scdo-agent/data run --name '+name+' --ledger https://scdo.com.au\n').encode()
def apply_agent(work,m,host,name):
 # Same verified fleet payload; explicit official ledger and erc8004=false before first run.
 config=Path(m.CONFIG_PATH)
 if not config.exists():atomic(config,m.CONFIG_TEXT.encode(),0o644)
 host.ensure_user();u=pwd.getpwnam(m.ACCOUNT)
 dest=Path(m.BIN_PATH);dest.parent.mkdir(parents=True,exist_ok=True)
 atomic(dest,(work/'scdo-agent').read_bytes(),0o755)
 data=Path(m.DATA_ROOT);data.mkdir(parents=True,exist_ok=True,mode=0o700)
 host.chown_tree(Path(m.HOME)/'.scdo-agent')
 if not m.identity_exists(host,name):
  run(['runuser','-u',m.ACCOUNT,'--','env','SCDO_AGENT_MODE=user',str(dest),'--lang','en','--data-dir',str(data),'init','--name',name,'--role','bookkeeping-node','--label','t460p-firstgen heartbeat-only=true erc8004=false'])
 # The init output is never logged. No wallet/pay/erc8004 command is invoked.
 unit=Path(m.UNIT_PATH)
 if not unit.exists():atomic(unit,m.UNIT_TEXT.encode())
 drop=Path('/etc/systemd/system')/('scdo-host-agent@'+name+'.service.d')/'90-t460p-ledger.conf'
 atomic(drop,ledger_dropin(name))
 run(['systemctl','daemon-reload'])
 n='scdo-host-agent@'+name+'.service'
 run(['systemctl','enable',n]);run(['systemctl','restart',n])
 state=Path(m.HOME)/'.scdo-agent/installer-state.json'
 atomic(state,json.dumps({'name':name,'version':'0.5.11','sha256':AGENT_SHA,'erc8004':False,'wallet':False}).encode(),0o600)
 os.chown(state,u.pw_uid,u.pw_gid)
 print('Ledger/bot identity preserved or initialized locally; explicit official ledger, no wallet or transactions.')

def atomic(p,data,mode=0o644):
 p=safe(p);p.parent.mkdir(parents=True,exist_ok=True);tmp=p.with_name(p.name+'.t460p-new')
 fd=os.open(tmp,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,mode)
 with os.fdopen(fd,'wb') as f:f.write(data);f.flush();os.fsync(f.fileno());os.fchmod(f.fileno(),mode)
 os.replace(tmp,p)
def service(name,exe,user,home=None):
 h=('Environment=HOME='+home+'\n') if home else ''
 text='[Unit]\nDescription=SCDO T460p '+name+' (no new mining)\nAfter=network-online.target\nWants=network-online.target\n[Service]\nUser='+user+'\n'+h+'ExecStart='+exe+'\nRestart=on-failure\nRestartSec=10\nTimeoutStopSec=180\nUMask=0077\nNoNewPrivileges=true\nPrivateTmp=true\nNice=10\n[Install]\nWantedBy=multi-user.target\n'
 atomic(Path('/etc/systemd/system')/name,text.encode())
def backup(p,name):
 stamp=time.strftime('%Y%m%dT%H%M%S',time.localtime())+'-'+str(os.getpid())
 b=Path('/var/backups/scdo-t460p')/stamp;b.mkdir(parents=True,mode=0o700);os.chmod(b.parent,0o700)
 paths=p['backup']+['/etc/scdo-agent/config.toml','/etc/systemd/system/scdo-host-agent@.service','/var/lib/scdoagent/.scdo-agent/bin/scdo-agent','/var/lib/scdoagent/.scdo-agent/installer-state.json']
 # Unit drop-ins may affect launch; copy locally, privately, never into public pack.
 for n in p['units']+['scdo-host-agent@'+name+'.service']:
  for base in ['/etc/systemd/system','/run/systemd/system','/usr/lib/systemd/system']:
   paths.append(base+'/'+n);paths.append(base+'/'+n+'.d')
 paths.extend(['/etc/scdo-t460p'])
 for s in dict.fromkeys(paths):
  f=safe(Path(s))
  if f.is_file():
   d=b/'files'/s.lstrip('/');d.parent.mkdir(parents=True,exist_ok=True,mode=0o700);shutil.copy2(f,d)
  elif f.is_dir():shutil.copytree(f,b/'files'/s.lstrip('/'),symlinks=True,dirs_exist_ok=True)
 states={n:unit_info(n) for n in p['units']+['scdo-host-agent@'+name+'.service']}
 atomic(b/'plan.json',json.dumps(p,indent=2).encode(),0o600);atomic(b/'units.json',json.dumps(states,indent=2).encode(),0o600)
 print('Private binary/config/unit backup: '+str(b)+' (NOT a chain DB snapshot; keys/data never removed)')
 return b,states

def package_dirs():
 # Root's private umask must not make public executable parents untraversable.
 for name in ['/opt/scdo-t460p','/opt/scdo-t460p/1.0.1','/var/lib/scdo-t460p']:
  p=safe(rp(name));p.mkdir(parents=True,exist_ok=True,mode=0o755)
  need(p.is_dir() and p.stat().st_uid==0,'Unsafe package-owned directory')
  os.chmod(p,0o755)

def ensure_user():
 try:
  known=pwd.getpwnam('scdot460p');need(known.pw_dir=='/var/lib/scdo-t460p/home','Existing scdot460p account has an unexpected home')
 except KeyError:run(['useradd','--system','--create-home','--home-dir','/var/lib/scdo-t460p/home','--shell','/usr/sbin/nologin','scdot460p'])
 return pwd.getpwnam('scdot460p')
def apply(p,work,m,host,name):
 b,states=backup(p,name)
 # No configuration or service changes until all downloads and preflights passed and backup completed.
 newunitfiles=[];changed=[]
 try:
  for n in p['units']:
   if unit_info(n):run(['systemctl','stop',n],timeout=210)
  # Recheck ports after controlled stop. Unknown processes are never killed.
  probe_ports([30368,18545,18551,8026,8027,8028,8029,8036,8037,8038,8039,8046,8047,8048,8049,8056,8057,8058,8059],[])
  if not p['classic_existing'] or not p['shard0_existing']:
   package_dirs();u=ensure_user()
  atomic(Path(p['nodebin']),(work/'node').read_bytes(),0o755);changed.append(p['nodebin'])
  if not p['classic_existing']:
   cfgdir=safe(Path('/etc/scdo-t460p'));cfgdir.mkdir(mode=0o750);os.chmod(cfgdir,0o750);os.chown(cfgdir,0,u.pw_gid)
   for i,n in enumerate(p['classic_units'],1):
    cfg=json.loads((work/('template'+str(i)+'.json')).read_text());port={1:8027,2:8028,3:8029,4:8026}[i]
    # Private P2P identity generated locally; output is captured, never logged.
    keyout=run([str(work/'client'),'key','--shard',str(i)]).stdout
    key=re.search(r'Private key:?\s+(0x[0-9a-fA-F]{64})',keyout);acc=re.search(r'Account:?\s+([1-4]S0[1-4][0-9a-fA-F]{38})',keyout)
    need(key and acc,'Local P2P identity generation failed (output withheld)')
    cfg['basic'].update(dataDir='t460p/Snode'+str(i),address='0.0.0.0:'+str(port),coinbase=acc.group(1))
    cfg['p2p']['privateKey']=key.group(1);cfg['p2p']['staticNodes']=MEL
    cfg['p2p'].pop('address',None)
    cfg['httpServer']['address']='127.0.0.1:'+str(port+10)
    cfg['wsserver']={'address':'127.0.0.1:'+str(port+20),'crossorigins':['localhost']}
    cf=Path('/etc/scdo-t460p/node'+str(i)+'.json');atomic(cf,json.dumps(cfg).encode(),0o640);os.chown(cf,0,u.pw_gid)
    service(n,p['nodebin']+' start -c '+str(cf)+' -m stop','scdot460p','/var/lib/scdo-t460p/home');newunitfiles.append('/etc/systemd/system/'+n)
  if not p['shard0_existing']:
   atomic(Path(p['geth']),(work/'geth').read_bytes(),0o755);changed.append(p['geth'])
   data=Path(p['data']);data.mkdir(parents=True,mode=0o700);os.chown(data,u.pw_uid,u.pw_gid)
   gen=Path('/opt/scdo-t460p/1.0.1/genesis.json');atomic(gen,(work/'genesis.json').read_bytes(),0o644)
   r=run(['runuser','-u','scdot460p','--',p['geth'],'--log.json','--datadir',str(data),'init',str(gen)],timeout=120)
   need(GENESIS_HASH in r.stdout+r.stderr,'Offline Shard0 genesis mismatch; data kept, service NOT started')
   args=[p['geth'],'--datadir',str(data),'--networkid','5680','--syncmode','full','--gcmode','archive','--cache','128','--maxpeers','10','--port','30368','--discovery.port','30368','--nat','none','--bootnodes',BOOT,'--discovery.dns','','--http','--http.addr','127.0.0.1','--http.port','18545','--http.api','eth,net,web3','--http.vhosts','localhost,127.0.0.1','--authrpc.addr','127.0.0.1','--authrpc.port','18551','--ipcdisable','--scdo.checkpoint.signers','0x0099ff8a23a260e32ccd1895f1c54f6bfb57a619','--scdo.checkpoint.threshold','1','--scdo.checkpoint.url','https://scdo.com.au/checkpoint/shard0/latest.json','--scdo.checkpoint.poll','30s']
   service(p['shard0_unit'],' '.join('""' if x=='' else x for x in args),'scdot460p');newunitfiles.append('/etc/systemd/system/'+p['shard0_unit'])
  else:
   drop=Path('/etc/systemd/system')/(p['shard0_unit']+'.d')/'90-t460p-checkpoint.conf'
   atomic(drop,('[Service]\nExecStart=\nExecStart='+' '.join(x if x else '""' for x in p['shard0_args'])+'\n').encode());newunitfiles.append(str(drop))
  run(['systemctl','daemon-reload'])
  for n in p['units']:run(['systemctl','enable',n]);run(['systemctl','start',n],timeout=210)
  m.selftest(str(work/'payload/scdo-agent'),json.loads((work/'manifest.json').read_text()),host)
  apply_agent(work,m,host,name)
  time.sleep(3)
  for n in p['units']+['scdo-host-agent@'+name+'.service']:need(run(['systemctl','is-active','--quiet',n],False).returncode==0,'Unit is not active: '+n)
  print('Upgrade applied; all five node services and Ledger/bot service active and enabled.')
  print('Active is NOT proof of chain catch-up or accepted Ledger heartbeats. Check status and two heartbeats five minutes apart.')
 except Exception:
  # Restore only package-swapped binaries/configs/units. Never restore/delete chain DB or identities.
  for n in p['units']:run(['systemctl','stop',n],False,210)
  for s in changed+newunitfiles:
   old=b/'files'/s.lstrip('/')
   if old.is_file():atomic(Path(s),old.read_bytes(),stat.S_IMODE(old.stat().st_mode))
   elif s in newunitfiles and Path(s).is_file():Path(s).unlink()
  run(['systemctl','daemon-reload'],False)
  for n,j in states.items():
   if n not in p['units']:continue
   if j.get('UnitFileState')!='enabled':run(['systemctl','disable',n],False)
   if j.get('ActiveState')=='active':run(['systemctl','start',n],False,210)
  print('FAILED: node binary/unit rollback attempted. All databases and agent identities retained. Inspect '+str(b)+' locally.',file=sys.stderr)
  raise
 status(p)
 print('Status: systemctl --no-pager status '+' '.join(p['units']+['scdo-host-agent@'+name+'.service']))

def rpc(port,method,params=None):
 req=urllib.request.Request('http://127.0.0.1:'+str(port),data=json.dumps({'jsonrpc':'2.0','id':1,'method':method,'params':params or []}).encode(),headers={'Content-Type':'application/json'})
 with urllib.request.urlopen(req,timeout=3) as r:j=json.load(r)
 need('result' in j,'RPC method unavailable: '+method)
 return j['result']
def status(p):
 results={};ok=True
 for n in p['units']:
  r=run(['systemctl','is-active',n],False);results[n]=r.stdout.strip();ok=ok and r.returncode==0
 try:
  cid=rpc(18545,'eth_chainId');zero=rpc(18545,'eth_getBlockByNumber',['0x0',False]);mining=rpc(18545,'eth_mining')
  results['shard0']={'chainId':cid,'genesis_hash':zero.get('hash'),'blockNumber':rpc(18545,'eth_blockNumber'),'peers':rpc(18545,'net_peerCount'),'syncing':rpc(18545,'eth_syncing'),'mining':mining}
  ok=ok and cid=='0x1630' and zero.get('hash')==GENESIS_HASH and mining is False
 except Exception:results['shard0']='RPC not ready or incompatible';ok=False
 for i,port in [(1,8037),(2,8038),(3,8039),(4,8036)]:
  try:
   j=rpc(port,'scdo_getInfo');results['classic'+str(i)]={'height':j.get('CurrentBlockHeight'),'rpc_port':port}
  except Exception:results['classic'+str(i)]='RPC not ready or nonstandard local port (configs preserved)';ok=False
 print(json.dumps(results,indent=2));print('Service/RPC availability is not full chain synchronization or Ledger acceptance.')
 return ok

def main():
 global ROOT
 p=argparse.ArgumentParser(description=__doc__);g=p.add_mutually_exclusive_group();g.add_argument('--apply',action='store_true');g.add_argument('--prepare',action='store_true',help='download and verify in a private temporary folder; no service/data changes');g.add_argument('--dry-run',action='store_true',help='read-only host layout and port preflight (default)');g.add_argument('--status',action='store_true',help='read-only local unit and RPC status')
 p.add_argument('--root',default='/',help='disposable read-only fixture root; --dry-run only')
 a=p.parse_args();ROOT=Path(a.root).absolute();need(ROOT==Path('/') or (a.dry_run and not a.apply and not a.prepare),'Fixture root is dry-run only')
 need(sys.version_info>=(3,10),'Python 3.10+ required');os.umask(0o077)
 if a.apply:need(os.geteuid()==0,'Use sudo for --apply')
 if ROOT==Path('/'):
  for cmd in ['systemctl','ss']:need(shutil.which(cmd),'Required existing command missing: '+cmd)
 layout=plan();print(json.dumps({k:v for k,v in layout.items() if k not in ('backup','shard0_args')},indent=2))
 print('Existing chain data/configs/keys preserved; no GPU, CUDA, zminer, wallet imports or DB wipes.')
 if a.status:
  need(ROOT==Path('/'),'Status requires the actual host');need(status(layout),'Some service/RPC checks are not ready; inspect preserved configuration and logs');return
 if not a.apply and not a.prepare:return
 if ROOT==Path('/'):
  mem={k:int(v.split()[0]) for l in Path('/proc/meminfo').read_text().splitlines() for k,v in [l.split(':',1)] if k in ['MemTotal','MemAvailable']}
  need(mem['MemTotal']>=7*1024*1024 and mem['MemAvailable']>=2*1024*1024,'Need >=8 GiB RAM and >=2 GiB currently available; no processes stopped')
  need(shutil.disk_usage('/var').free>=20*1024**3,'Need >=20 GiB free on /var (minimum only; allow much more for five chains)')
 with tempfile.TemporaryDirectory(prefix='scdo-t460p-') as d:
  work=Path(d);prepare(work);m,host,name=agent_preflight(work)
  if a.prepare:print('Prepare verification complete; temporary downloads removed. No installed files, keys or services changed.');return
  lock=os.open('/var/lock/scdo-t460p-upgrade.lock',os.O_RDWR|os.O_CREAT|os.O_NOFOLLOW,0o600)
  try:
   fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB);layout=plan();agent_preflight(work);apply(layout,work,m,host,name)
  finally:os.close(lock)
if __name__=='__main__':
 try:main()
 except (Refusal,OSError,ValueError,KeyError,tarfile.TarError,subprocess.TimeoutExpired) as e:
  print('REFUSED: '+(str(e) if isinstance(e,Refusal) else type(e).__name__+'; inspect locally, private details withheld'),file=sys.stderr);sys.exit(2)
