#!/bin/sh
set -e

echo "Waiting for ngrok to start..."
sleep 5

NGROK_URL=""
RETRIES=10

while [ -z "$NGROK_URL" ] && [ "$RETRIES" -gt 0 ]; do
    NGROK_URL=$(curl -s http://ngrok:4040/api/tunnels | grep -o '"public_url":"https://[^"]*"' | head -1 | cut -d'"' -f4)
    if [ -z "$NGROK_URL" ]; then
        echo "Waiting for tunnel..."
        sleep 2
        RETRIES=$((RETRIES - 1))
    fi
done

if [ -z "$NGROK_URL" ]; then
    echo "ERROR: Could not get ngrok URL"
    exit 1
fi

touch /app/.env.local
sed -i '/^OUTSIDE_URL=/d' /app/.env.local
echo "OUTSIDE_URL=$NGROK_URL" >> /app/.env.local

echo "Ngrok URL: $NGROK_URL"
echo "Written to .env.local"
