apiVersion: v1
kind: Pod
metadata:
  name: debug-tsnet
spec:
  shareProcessNamespace: true
  containers:
  - name: tailscale
    image: ghcr.io/tailscale/tailscale:v1.50.1
    imagePullPolicy: IfNotPresent
    command:
    - /bin/sh
    - -c
    - |
      export PATH=$PATH:/tailscale/bin
      export PINGIP="100.64.0.20"
      export PROCESS_TO_WAIT_FOR="bash"
      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 Tailscale to connect properly"
      until tailscale --socket=/tmp/tailscaled.sock status; do
        echo "... Tailscale not ready yet"
        sleep 2
      done

      echo "==> Checking Tailscale connection to target"
      until tailscale --socket=/tmp/tailscaled.sock ping $PINGIP; do
        echo "==> ... No Tailscale connection yet"
        sleep 2
      done

      echo "==> Checking network connection to brunnernas"
      until ping -c1 $PINGIP; do
        echo "==> ... No network connection yet"
        sleep 2
      done

      echo "==> Connected! Waiting for main container to exit"
      while pidof $PROCESS_TO_WAIT_FOR > /dev/null; do sleep 1; done

      echo "==> Main container ended - stopping Tailscale"
      kill -s SIGINT $TS_PID
      wait ${TS_PID}
    env:
    - name: TS_AUTH_KEY
      valueFrom:
        secretKeyRef:
          key: TS_AUTH_KEY
          name: tailscale-auth-backup
    resources: {}
    securityContext:
      capabilities:
        add:
        - NET_ADMIN
  - name: debugger
    image: docker.io/nicolaka/netshoot:latest
    imagePullPolicy: Always
    command: ["/bin/bash"]
    args: ["-c", "while true; do ping -i 10 localhost; sleep 60;done"]
    resources: {}
