apiVersion: policy.jspolicy.com/v1beta1
kind: JsPolicy
metadata:
  name: copy-tailscale-auth-secret.tbrnt.ch
spec:
  operations: ["CREATE"]
  resources: ["pods"]
  scope: Namespaced
  objectSelector:
    matchLabels:
      k8upjob: "true"
  type: Controller
  javascript: |
    const authsecret = get("Secret", "v1", "k8up/tailscale-auth-backup");

    authsecret.metadata.namespace = request.namespace
    delete authsecret.metadata.uid
    delete authsecret.metadata.resourceVersion
    delete authsecret.metadata.annotations
    delete authsecret.metadata.labels
    delete authsecret.metadata.creationTimestamp

    authsecret.metadata.ownerReferences = [{
      apiVersion: "v1",
      kind: "Pod",
      name: request.name,
      uid: request.object.metadata.uid
    }]

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