#!/bin/bash
# start_services.sh — เปิด web server + cloudflared tunnel สำหรับ stock dashboard
# รันตอน boot หรือสั่งด้วยมือ: ./start_services.sh

BASE_DIR="/home/kit001/stock"
BIN="$HOME/.local/bin/cloudflared"
PORT=8080
PID_DIR="$BASE_DIR"
WEBLOG="$BASE_DIR/webserver.log"
TUNNELLOG="$BASE_DIR/tunnel.log"

echo "🚀 เริ่ม StockBotKit web services..."

# 1) Web server (python http.server) — เสิร์ฟ dashboard
if pgrep -f "http.server $PORT" > /dev/null 2>&1; then
    echo "✅ Web server กำลังรันอยู่แล้ว (port $PORT)"
else
    nohup python3 -m http.server $PORT --directory "$BASE_DIR" > "$WEBLOG" 2>&1 &
    sleep 1
    echo "✅ web server เปิดแล้ว (port $PORT)"
fi

# 2) Cloudflare tunnel — เปิดให้เข้าจากข้างนอกได้
if pgrep -f "cloudflared tunnel" > /dev/null 2>&1; then
    echo "✅ Cloudflare tunnel กำลังรันอยู่แล้ว"
else
    nohup $BIN tunnel --url http://localhost:$PORT --no-autoupdate > "$TUNNELLOG" 2>&1 &
    sleep 5
    echo "✅ Cloudflare tunnel เปิดแล้ว"
fi

# 3) โชว์ URL ล่าสุด
URL=$(grep -oE "https://[a-zA-Z0-9-]+\.trycloudflare\.com" "$TUNNELLOG" 2>/dev/null | tail -1)
if [ -n "$URL" ]; then
    echo ""
    echo "🌐 Dashboard link:"
    echo "   $URL/dashboard_thai.html"
else
    echo "⏳ ยังไม่เจอ URL — รออีกครู่แล้วดู tunnel.log ครับ"
fi
echo ""
echo "📄 Log: $TUNNELLOG, $WEBLOG"