from pathlib import Path
import subprocess,json,time,os
root=Path('/home/lighthouse/esp32-dev/.cache/agent-navigator-0.6b')
assert subprocess.check_output(['git','rev-parse','HEAD'],cwd=root,text=True).strip()=='54e987a1f180e65bd8afb7c231d0ef6d1d449a95'
backup=root/'.cache/deployment';backup.mkdir(parents=True,exist_ok=True)
dropin=Path.home()/'.config/systemd/user/device-gateway.service.d/zzz-agent-navigator-0.6b.conf'
pager=Path.home()/'.pi/agent/extensions/device-lab-pager.ts'
state={'previous_dropin':dropin.read_text() if dropin.exists() else None,'previous_pager':os.readlink(pager) if pager.is_symlink() else None,'time':time.time()}
(backup/'rollback.json').write_text(json.dumps(state,indent=2)+'\n')
dropin.parent.mkdir(parents=True,exist_ok=True)
dropin.write_text('[Service]\nWorkingDirectory='+str(root)+'\nExecStart=\nExecStart='+str(root/'scripts/run-server.sh')+'\n')
assert pager.is_symlink(), 'Preserve unexpected non-symlink pager installation'
pager.unlink();pager.symlink_to(root/'integrations/pi/device-lab-pager.ts')
subprocess.run(['systemctl','--user','daemon-reload'],check=True)
subprocess.run(['systemctl','--user','restart','device-gateway.service'],check=True)
subprocess.run(['systemctl','--user','is-active','device-gateway.service'],check=True)
print('Candidate Gateway deployed; existing environment/port/auth retained; rollback saved')
