apiVersion: policy.jspolicy.com/v1beta1
kind: JsPolicy
metadata:
  name: copy-headscale-config-to-webui.tbrnt.ch
spec:
  operations: ["CREATE"]
  resources: ["deployments"]
  scope: Namespaced
  objectSelector:
    matchLabels:
      app: headscale-webui
  type: Controller
  javascript: |
    const configmap = get("ConfigMap", "v1", "headscale/headscale-etc");

    configmap.metadata.namespace = "headscale-webui"
    configmap.metadata.name = "headscale-etc-copy"
    delete configmap.metadata.uid
    delete configmap.metadata.resourceVersion
    delete configmap.metadata.annotations
    delete configmap.metadata.labels
    delete configmap.metadata.creationTimestamp

    const result = create(configmap);
    if (!result.ok) {
      // check for a specific error type
      if (result.reason === "AlreadyExists") {
        warn(`ConfigMap already exists`);
      } else {
        warn(`Error creating ConfigMap (Reason ${result.reason}): ${result.message}`);
      }
    } else {
      print("Created ConfigMap");
    }