apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: inject-tailscale
spec:
  rules:
    - name: inject-tailscale
      match:
        resources:
          kinds:
            - Pod
          selector:
            matchLabels:
              k8upjob: "true"
      mutate:
        patchStrategicMerge:
          spec:
            shareProcessNamespace: true
            containers:
              - name: ts-sidecar
                imagePullPolicy: IfNotPresent
                image: ghcr.io/tailscale/tailscale:v1.38.3
                command:
                  - /bin/sh
                  - -c
                  - |
                    export PATH=$PATH:/tailscale/bin
                    set -e

                    if [[ ! -d /dev/net ]]; then
                      mkdir -p /dev/net
                    fi
                    if [[ ! -c /dev/net/tun ]]; then
                      mknod /dev/net/tun c 10 200
                    fi

                    echo "Starting tailscaled in background"
                    tailscaled --socket=/tmp/tailscaled.sock --state=mem: --statedir=/tmp &
                    TS_PID=$!

                    echo "Running tailscale up"
                    tailscale --socket=/tmp/tailscaled.sock up --authkey=${TS_AUTH_KEY} --accept-dns=false --login-server https://headscale.tbrnt.ch

                    echo "Waiting for K8up to exit"
                    while pidof k8up > /dev/null; do sleep 1; done

                    echo "K8up ended - stopping tailscale"
                    kill -s SIGINT $TS_PID
                    wait ${TS_PID}
                env:
                  - name: TS_AUTH_KEY
                    valueFrom:
                      secretKeyRef:
                        name: tailscale-auth-backup
                        key: TS_AUTH_KEY
                securityContext:
                  capabilities:
                    add:
                      - NET_ADMIN
