#!/usr/bin/env bash
#
# onx-hostname-get — Sunucu FQDN/hostname bilgisini JSON döner.
#
# Stdin (JSON): {} (no args)
#
# Stdout (JSON):
#   {
#     "ok": true,
#     "hostname": "mail.onoxsoft.com.tr",       // hostname --fqdn (transient + static aynıysa bu)
#     "static_hostname": "mail.onoxsoft.com.tr", // /etc/hostname
#     "transient_hostname": "mail.onoxsoft.com.tr", // kernel runtime
#     "pretty_hostname": "ONOXSOFT Panel",       // /etc/machine-info PRETTY_HOSTNAME (opsiyonel)
#     "kernel_release": "5.14.0-...",
#     "machine_id": "...",
#     "fqdn": "mail.onoxsoft.com.tr",            // hostname -f resolver sonucu
#     "reverse_dns": "vmi...contaboserver.net",  // PTR (dig -x primary IP)
#     "primary_ip": "149.102.145.172",
#     "ptr_matches_hostname": false              // fqdn == reverse_dns mi (mail için kritik)
#   }
#
# Exit: 0 (her durumda)

INPUT=$(cat 2>/dev/null || echo '{}')

STATIC=$(hostnamectl --static 2>/dev/null || cat /etc/hostname 2>/dev/null || echo "unknown")
TRANSIENT=$(hostnamectl --transient 2>/dev/null || hostname 2>/dev/null || echo "unknown")
PRETTY=$(hostnamectl --pretty 2>/dev/null || echo "")
KERNEL=$(uname -r 2>/dev/null || echo "unknown")
MACHINE_ID=$(cat /etc/machine-id 2>/dev/null || echo "")
FQDN=$(hostname -f 2>/dev/null || echo "$STATIC")

# Primary IP — default route üzerindeki interface'in IP'si
PRIMARY_IFACE=$(ip route show default 2>/dev/null | head -1 | grep -oE 'dev [a-z0-9]+' | awk '{print $2}')
PRIMARY_IP=""
if [[ -n "$PRIMARY_IFACE" ]]; then
    PRIMARY_IP=$(ip -4 -o addr show "$PRIMARY_IFACE" 2>/dev/null | awk '{print $4}' | head -1 | awk -F/ '{print $1}')
fi

# Reverse DNS (PTR) — primary IP üzerinden
REVERSE_DNS=""
if [[ -n "$PRIMARY_IP" ]] && command -v dig >/dev/null 2>&1; then
    REVERSE_DNS=$(dig -x "$PRIMARY_IP" +short +timeout=2 2>/dev/null | head -1 | sed 's/\.$//')
fi
[[ -z "$REVERSE_DNS" ]] && REVERSE_DNS="(çözülemedi)"

# Match check — mail server için PTR == FQDN olmalı (FCrDNS)
PTR_MATCH="false"
if [[ -n "$FQDN" && "$REVERSE_DNS" == "$FQDN" ]]; then
    PTR_MATCH="true"
fi

jq -nc \
    --arg hostname "$TRANSIENT" \
    --arg static "$STATIC" \
    --arg transient "$TRANSIENT" \
    --arg pretty "$PRETTY" \
    --arg kernel "$KERNEL" \
    --arg machine_id "$MACHINE_ID" \
    --arg fqdn "$FQDN" \
    --arg reverse_dns "$REVERSE_DNS" \
    --arg primary_ip "$PRIMARY_IP" \
    --argjson ptr_match $([ "$PTR_MATCH" = "true" ] && echo true || echo false) \
    '{ok:true, hostname:$hostname, static_hostname:$static, transient_hostname:$transient, pretty_hostname:$pretty, kernel_release:$kernel, machine_id:$machine_id, fqdn:$fqdn, reverse_dns:$reverse_dns, primary_ip:$primary_ip, ptr_matches_hostname:$ptr_match}'

exit 0
