#!/bin/bash

ENDPOINT="https://root360.com.br/monitor-agent-event.php"
AUTH_ENDPOINT="https://root360.com.br/monitor-agent-auth.php"
DEVICE_FILE="$HOME/.root360-monitor-device-id"

if [ -f "$DEVICE_FILE" ]; then
  DEVICE_ID="$(head -n 1 "$DEVICE_FILE" | tr -d '\r\n')"
fi

if [ -z "$DEVICE_ID" ]; then
  if command -v uuidgen >/dev/null 2>&1; then
    DEVICE_ID="$(uuidgen)"
  else
    DEVICE_ID="$(date +%s)-$RANDOM-$RANDOM"
  fi
  printf "%s" "$DEVICE_ID" > "$DEVICE_FILE"
fi

printf "Digite seu nome: "
read -r NAME
printf "Digite seu e-mail: "
read -r EMAIL
printf "Digite sua chave de ativação: "
read -r ACTIVATION_KEY

if [ -z "$NAME" ] || [ -z "$EMAIL" ] || [ -z "$ACTIVATION_KEY" ]; then
  printf "Nome, e-mail e chave de ativação são obrigatórios.\n"
  exit 1
fi

json_escape() {
  printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}

send_event() {
  local event_name="$1"
  local details="$2"
  local session_token="$3"
  local active_seconds="$4"
  local payload
  payload="{\"email\":\"$(json_escape "$EMAIL")\",\"platform\":\"macos\",\"event\":\"$(json_escape "$event_name")\",\"device_id\":\"$(json_escape "$DEVICE_ID")\",\"details\":\"$(json_escape "$details")\",\"session_token\":\"$(json_escape "$session_token")\",\"active_seconds\":$active_seconds}"
  curl -sS --max-time 12 -X POST "$ENDPOINT" -H "Content-Type: application/json" -d "$payload" >/dev/null
}

auth_app() {
  local payload
  payload="{\"name\":\"$(json_escape "$NAME")\",\"email\":\"$(json_escape "$EMAIL")\",\"activation_key\":\"$(json_escape "$ACTIVATION_KEY")\",\"platform\":\"macos\",\"device_id\":\"$(json_escape "$DEVICE_ID")\"}"
  AUTH_RESPONSE="$(curl -sS --max-time 12 -X POST "$AUTH_ENDPOINT" -H "Content-Type: application/json" -d "$payload")"
  SESSION_TOKEN="$(printf '%s' "$AUTH_RESPONSE" | sed -n 's/.*"session_token":"\([^"]*\)".*/\1/p')"
  HEARTBEAT_SECONDS="$(printf '%s' "$AUTH_RESPONSE" | sed -n 's/.*"heartbeat_seconds":\([0-9]*\).*/\1/p')"
  if [ -z "$SESSION_TOKEN" ]; then
    return 1
  fi
  if [ -z "$HEARTBEAT_SECONDS" ] || [ "$HEARTBEAT_SECONDS" -lt 60 ] 2>/dev/null; then
    HEARTBEAT_SECONDS=600
  fi
  return 0
}

is_online() {
  if ping -c 1 -W 2 1.1.1.1 >/dev/null 2>&1; then
    return 0
  fi
  if curl -sS -I --max-time 6 "https://root360.com.br" >/dev/null 2>&1; then
    return 0
  fi
  return 1
}

if is_online; then
  ONLINE=1
else
  ONLINE=0
fi

if ! auth_app; then
  printf "Falha na autenticação. Confira nome, e-mail e chave de ativação.\n"
  exit 1
fi

STARTED_AT="$(date +%s)"
LAST_HEARTBEAT_AT="$(date +%s)"
send_event "agent_started" "monitor_iniciado" "$SESSION_TOKEN" 0
if [ "$ONLINE" -eq 0 ]; then
  send_event "connection_lost" "sem_conexao_na_inicializacao" "$SESSION_TOKEN" 0
fi

printf "Monitor Root360 ativo. Pressione Control+C para encerrar.\n"
while true; do
  sleep 15
  NOW="$(date +%s)"
  ACTIVE_SECONDS=$((NOW - STARTED_AT))
  if is_online; then
    CURRENT=1
  else
    CURRENT=0
  fi

  if [ "$ONLINE" -eq 1 ] && [ "$CURRENT" -eq 0 ]; then
    send_event "connection_lost" "conexao_caiu" "$SESSION_TOKEN" "$ACTIVE_SECONDS"
    printf "Conexão caiu.\n"
  elif [ "$ONLINE" -eq 0 ] && [ "$CURRENT" -eq 1 ]; then
    send_event "connection_restored" "conexao_restabelecida" "$SESSION_TOKEN" "$ACTIVE_SECONDS"
    printf "Conexão restabelecida.\n"
  fi

  if [ $((NOW - LAST_HEARTBEAT_AT)) -ge "$HEARTBEAT_SECONDS" ]; then
    send_event "heartbeat" "monitor_ativo" "$SESSION_TOKEN" "$ACTIVE_SECONDS"
    LAST_HEARTBEAT_AT="$NOW"
  fi

  ONLINE="$CURRENT"
done
