#!/bin/bash

URL="http://localhost:8080/health"
LOG_FILE="/home/ec2-user/projects/ghaymah-exam-moustafa-medhat-sre/q1-deploy-monitor/health.log"

touch "$LOG_FILE"

echo "===== Health Monitor Started =====" >> "$LOG_FILE"

while true
do
    START=$(date +%s%3N)

    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$URL")

    END=$(date +%s%3N)
    RESPONSE_TIME=$((END - START))

    TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")

    if [ "$HTTP_CODE" -eq 200 ]; then
        STATUS="UP"
    else
        STATUS="DOWN"
    fi

    echo "[$TIMESTAMP] Status=$STATUS | HTTP=$HTTP_CODE | Response=${RESPONSE_TIME}ms" >> "$LOG_FILE"

    sleep 30
done
