#!/bin/bash

# =====================================================
# Script update leaderboard snapshot untuk Piala Dunia 2026
# Secret key dibaca dari environment variable CRON_SECRET
# =====================================================

# Pastikan environment variable CRON_SECRET tersedia
if [ -z "$CRON_SECRET" ]; then
    echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR: CRON_SECRET environment variable not set" >> /var/log/update_leaderboard.log
    exit 1
fi

SECRET="$CRON_SECRET"

# URL endpoint (sesuaikan dengan path aplikasi Anda)
URL="http://localhost/bagan_wc_pro/api.php?action=update_leaderboard_snapshot"

# File log untuk mencatat hasil eksekusi
LOG_FILE="/var/log/update_leaderboard.log"

# Panggil endpoint menggunakan curl dengan header secret
RESPONSE=$(curl -s -X GET "$URL" -H "X-Cron-Secret: $SECRET")

# Cek apakah berhasil (mengandung status success)
if echo "$RESPONSE" | grep -q '"status":"success"'; then
    echo "$(date '+%Y-%m-%d %H:%M:%S') - SUCCESS: Leaderboard snapshot updated." >> "$LOG_FILE"
else
    echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR: Failed to update leaderboard. Response: $RESPONSE" >> "$LOG_FILE"
fi