apiVersion: policy.jspolicy.com/v1beta1
kind: JsPolicy
metadata:
  name: inject-tailscale-sidecar.tbrnt.ch
spec:
  type: Mutating
  operations: ["CREATE"]
  resources: ["pods"]
  scope: Namespaced
  objectSelector:
    matchLabels:
      k8upjob: "true"
  javascript: |
    const shellScript =
        'export PATH=$PATH:/tailscale/bin\n' +
        'export PINGIP="100.64.0.20"\n' +
        'export PROCESS_TO_WAIT_FOR="k8up"\n' +
        'set -e\n\n' +
        'if [[ ! -d /dev/net ]]; then\n' +
        '    mkdir -p /dev/net\n' +
        'fi\n' +
        'if [[ ! -c /dev/net/tun ]]; then\n' +
        '    mknod /dev/net/tun c 10 200\n' +
        'fi\n\n' +
        'echo "==> Starting tailscaled in background"\n' +
        'tailscaled --socket=/tmp/tailscaled.sock --state=mem: --statedir=/tmp &\n' +
        'TS_PID=$!\n\n' +
        'echo "==> Running tailscale up"\n' +
        'tailscale --socket=/tmp/tailscaled.sock up --authkey=${TS_AUTH_KEY} --accept-dns=false --login-server https://headscale.tbrnt.ch\n\n' +
        'echo "==> Waiting for Tailscale to connect properly"\n' +
        'until tailscale --socket=/tmp/tailscaled.sock status; do\n' +
        '    echo "... Tailscale not ready yet"\n' +
        '    sleep 1\n' +
        'done\n\n' +
        'echo "==> Checking Tailscale connection to target"\n' +
        'until tailscale --socket=/tmp/tailscaled.sock ping $PINGIP; do\n' +
        '    echo "==> ... No Tailscale connection yet"\n' +
        '    sleep 1\n' +
        'done\n\n' +
        'echo "==> Checking network connection to target"\n' +
        'until ping -c1 $PINGIP; do\n' +
        '    echo "==> ... No network connection yet"\n' +
        '    sleep 1\n' +
        'done\n\n' +
        'echo "==> Connected! Waiting for main container to exit"\n' +
        'while pidof $PROCESS_TO_WAIT_FOR > /dev/null; do sleep 1; done\n\n' +
        'echo "==> Main container ended - stopping Tailscale"\n' +
        'kill -s SIGINT $TS_PID\n' +
        'wait ${TS_PID}';

    request.object.spec.shareProcessNamespace = true
    request.object.spec.containers.push({
      name: "ts-sidecar",
      imagePullPolicy: "IfNotPresent",
      image: "ghcr.io/tailscale/tailscale:v1.52.0",
      command: ["/bin/sh", "-c", shellScript],
      env: [
        {
          name: "TS_AUTH_KEY",
          valueFrom: {
            secretKeyRef: {
              name: "tailscale-auth-backup",
              key: "TS_AUTH_KEY"
            }
          }
        }
      ],
      securityContext: {
        capabilities: {
          add: [ "NET_ADMIN" ]
        }
      }
    });
    mutate(request.object);
