#!/bin/bash
# ANAF Page Monitor - Simple hash-based change detection
# Checks configured pages and reports changes

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="$SCRIPT_DIR/config.json"
HASHES_FILE="$SCRIPT_DIR/hashes.json"
LOG_FILE="$SCRIPT_DIR/monitor.log"

# Initialize hashes file if not exists
if [ ! -f "$HASHES_FILE" ]; then
    echo "{}" > "$HASHES_FILE"
fi

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

check_page() {
    local id="$1"
    local name="$2"
    local url="$3"
    
    # Fetch page content and compute hash
    local content=$(curl -s -L --max-time 30 "$url" 2>/dev/null)
    if [ -z "$content" ]; then
        log "ERROR: Failed to fetch $id ($url)"
        return 1
    fi
    
    local new_hash=$(echo "$content" | sha256sum | cut -d' ' -f1)
    local old_hash=$(jq -r ".[\"$id\"] // \"\"" "$HASHES_FILE")
    
    if [ "$old_hash" = "" ]; then
        # First time seeing this page
        log "INIT: $id - storing initial hash"
        jq ". + {\"$id\": \"$new_hash\"}" "$HASHES_FILE" > "$HASHES_FILE.tmp" && mv "$HASHES_FILE.tmp" "$HASHES_FILE"
        return 0
    fi
    
    if [ "$new_hash" != "$old_hash" ]; then
        log "CHANGE DETECTED: $id - $name"
        log "  URL: $url"
        log "  Old hash: $old_hash"
        log "  New hash: $new_hash"
        
        # Update stored hash
        jq ". + {\"$id\": \"$new_hash\"}" "$HASHES_FILE" > "$HASHES_FILE.tmp" && mv "$HASHES_FILE.tmp" "$HASHES_FILE"
        
        # Output change for notification
        echo "CHANGE:$id:$name:$url"
        return 2
    fi
    
    log "OK: $id - no changes"
    return 0
}

main() {
    log "=== Starting ANAF monitor check ==="
    
    local changes=""
    
    # Read config and check each page
    while IFS= read -r page; do
        id=$(echo "$page" | jq -r '.id')
        name=$(echo "$page" | jq -r '.name')
        url=$(echo "$page" | jq -r '.url')
        
        result=$(check_page "$id" "$name" "$url")
        if [ -n "$result" ]; then
            changes="$changes$result\n"
        fi
        
        # Small delay between requests
        sleep 2
    done < <(jq -c '.pages[]' "$CONFIG_FILE")
    
    log "=== Monitor check complete ==="
    
    # Output changes (if any) for the caller to handle
    if [ -n "$changes" ]; then
        echo -e "$changes"
    fi
}

main "$@"
