#!/bin/bash

CLIENT_ID="your_client_id_here"
CLIENT_SECRET="your_client_secret_here"
CHANNEL_NAME="ninja"

# 1. Get OAuth Token
TOKEN_RESPONSE=$(curl -s -X POST "https://twitch.tv" \
  -d "client_id=${CLIENT_ID}" \
  -d "client_secret=${CLIENT_SECRET}" \
  -d "grant_type=client_credentials")

# Parse token using awk
ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" | awk -F'"access_token":"' '{print $2}' | awk -F'"' '{print $1}')

if [ -z "$ACCESS_TOKEN" ]; then
  echo "Error: Failed to obtain access token."
  exit 1
fi

# 2. Query Streams API
STREAM_RESPONSE=$(curl -s -X GET "https://twitch.tv{CHANNEL_NAME}" \
  -H "Client-ID: ${CLIENT_ID}" \
  -H "Authorization: Bearer ${ACCESS_TOKEN}")

# 3. Use awk to check if the 'data' array contains a 'user_id' field
# If 'user_id' exists in the raw text response, the stream is live
IS_LIVE=$(echo "$STREAM_RESPONSE" | awk '/"user_id":/ {print "LIVE"}')

if [ "$IS_LIVE" == "LIVE" ]; then
  # Basic metadata extraction using awk regex fields
  TITLE=$(echo "$STREAM_RESPONSE" | awk -F'"title":"' '{print $2}' | awk -F'","' '{print $1}')
  GAME=$(echo "$STREAM_RESPONSE" | awk -F'"game_name":"' '{print $2}' | awk -F'","' '{print $1}')
  VIEWERS=$(echo "$STREAM_RESPONSE" | awk -F'"viewer_count":' '{print $2}' | awk -F',' '{print $1}')

  echo "STATUS: LIVE 🔴"
  echo "Title:  $TITLE"
  echo "Game:   $GAME"
  echo "Viewers: $VIEWERS"
else
  echo "STATUS: OFFLINE 😴"
fi

