#!/bin/bash

# Initial login
sleep 2
tailscale up --authkey="$(cat /data/modalai/tailscale.key)" --hostname="voxl2-$(cat /sys/devices/soc0/serial_number)" --accept-dns=false

# Warm up Tailscale paths immediately so peers start talking fast.
for i in 1 2 3; do
    PEERS=$(tailscale status --json 2>/dev/null | python3 -c "
import json,sys
try:
    data=json.load(sys.stdin)
    for p in data.get('Peer',{}).values():
        if p.get('Online'):
            ips=p.get('TailscaleIPs',[])
            if ips: print(ips[0])
except: pass" 2>/dev/null)

    for peer in $PEERS; do
        tailscale ping -c 1 --timeout=3s "$peer" &>/dev/null &
    done
    wait
    sleep 2
done

# Keepalive loop: ping online peers every 25 seconds
while true; do
    PEERS=$(tailscale status --json 2>/dev/null | python3 -c "
import json,sys
try:
    data=json.load(sys.stdin)
    for p in data.get('Peer',{}).values():
        if p.get('Online'):
            ips=p.get('TailscaleIPs',[])
            if ips: print(ips[0])
except: pass" 2>/dev/null)

    for peer in $PEERS; do
        tailscale ping -c 1 --timeout=5s "$peer" &>/dev/null &
    done

    sleep 25
done
