import sys,json,subprocess
from artifact_install import ArtifactInstaller

class NotificationInstaller(ArtifactInstaller):
    def prepare(self):
        super().prepare()
        self.save('indexes',dict(schemaUnchanged=True))
    def test(self):
        self.guard();image=json.loads((self.root/'built.json').read_text())['image']
        args=['docker','run','--rm','--pull=never','--runtime=runc','--network=none','--read-only','--cpus=2','--memory=8g','--pids-limit=256','--tmpfs','/tmp:size=256m','-e','NVIDIA_VISIBLE_DEVICES=void','-e','PYTHONDONTWRITEBYTECODE=1','-e','OPENBLAS_NUM_THREADS=1','-v',str(self.root)+':/work','--entrypoint','python3',image,'-B','-c',"import sys,unittest;sys.path[:0]=['/work/tests','/opt/contextra'];s=unittest.TestSuite(unittest.defaultTestLoader.loadTestsFromName(n) for n in ('test_fight_notification','test_fight_notification_runtime'));r=unittest.TextTestRunner(verbosity=2).run(s);raise SystemExit(not r.wasSuccessful())"]
        p=subprocess.run(args,capture_output=True,timeout=120)
        (self.root/'test.log').write_bytes(p.stdout+p.stderr)
        self.save('test-result',dict(exit_code=p.returncode))
        if p.returncode:raise RuntimeError('CANDIDATE_TEST_FAILED')
    def activate(self):
        assert json.loads((self.root/'test-result.json').read_text())['exit_code']==0
        super().activate()

root,action=sys.argv[1:]
assert action in ('prepare','build','test','activate','verify')
getattr(NotificationInstaller(root,'icerti-ai2'),action)()
