import sys,json
d=json.load(sys.stdin); spec=d["spec"]["template"]["spec"]; img=spec["containers"][0]["image"]
spec["volumes"]=[v for v in spec.get("volumes",[]) if v.get("name") not in ("webdist","webassets")]
spec["volumes"]+=[{"name":"webdist","emptyDir":{}},{"name":"webassets","configMap":{"name":"authentik-web-assets"}}]
script=("set -e\n cp -r /web/dist/. /wd/\n cp /assets/dezky-logo.svg /wd/assets/icons/dezky-logo.svg\n"
        " cp /assets/dezky-bg.svg /wd/assets/icons/dezky-bg.svg\n cp /assets/dezky-favicon.svg /wd/assets/icons/dezky-favicon.svg\n"
        " grep -rl 'Powered by authentik' /wd --include='*.js' | while read f; do sed -i 's/Powered by authentik/Powered by Dezky/g' \"$f\"; done\n echo rebrand-done")
ic=[c for c in spec.get("initContainers",[]) if c.get("name")!="dezky-rebrand"]
ic.append({"name":"dezky-rebrand","image":img,"command":["sh","-c",script],"volumeMounts":[{"name":"webdist","mountPath":"/wd"},{"name":"webassets","mountPath":"/assets"}]})
spec["initContainers"]=ic
c0=spec["containers"][0]
c0["volumeMounts"]=[m for m in c0.get("volumeMounts",[]) if m.get("name")!="webdist"]
c0["volumeMounts"].append({"name":"webdist","mountPath":"/web/dist"})
json.dump(d,sys.stdout)
