#!/bin/bash
# admin-hosting.sh -- Hosting Manager
TOOL_NAME="admin-hosting"; TOOL_VERSION="2.0.0"; TOOL_TIER=2; TOOL_BIRD="swan"
TOOL_LOG="/opt/binary/logs/tools/${TOOL_NAME}.log"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
if [[ -f "${SCRIPT_DIR}/common.sh" ]]; then source "${SCRIPT_DIR}/common.sh"
elif [[ -f "${SCRIPT_DIR}/../common.sh" ]]; then source "${SCRIPT_DIR}/../common.sh"
else echo "FATAL: common.sh not found" >&2; exit 1; fi
export BIRD_ID="${TOOL_BIRD}"

_do_send_impl() {
    echo "=== Hosting Status: ${NODE_ID} ==="
    echo "  Nginx: $(systemctl is-active nginx 2>/dev/null || echo 'not installed')"
    echo "  PHP-FPM: $(systemctl is-active php-fpm 2>/dev/null || echo 'not installed')"
    if command -v nginx &>/dev/null; then
        echo "  Sites enabled:"; ls /etc/nginx/conf.d/*.conf 2>/dev/null | wc -l | awk '{print "    " $1 " configs"}'
    fi
    tool_audit "send" "node=${NODE_ID}"
}
_do_status_impl() {
    local nginx="not_installed" php="not_installed"
    systemctl cat nginx.service &>/dev/null && nginx=$(systemctl is-active nginx 2>/dev/null)
    systemctl cat php-fpm.service &>/dev/null && php=$(systemctl is-active php-fpm 2>/dev/null)
    local s="healthy"; [ "$nginx" != "active" ] && [ "$nginx" != "not_installed" ] && s="degraded"
    echo "{\"tool\":\"${TOOL_NAME}\",\"node\":\"${NODE_ID}\",\"status\":\"${s}\",\"nginx\":\"${nginx}\",\"php_fpm\":\"${php}\",\"checked_at\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}"
}
_do_digest_impl() { _do_send_impl; }
_do_flush_impl() { [ -f "$TOOL_LOG" ] && truncate -s 0 "$TOOL_LOG"; }
tool_help() { echo "${TOOL_NAME} v${TOOL_VERSION} -- Hosting Manager"; }
do_send()   { tool_wrap "send"   _do_send_impl "$@"; }
do_status() { tool_wrap "status" _do_status_impl "$@"; }
do_digest() { tool_wrap "digest" _do_digest_impl "$@"; }
do_flush()  { tool_wrap "flush"  _do_flush_impl "$@"; }
tool_init; trap 'tool_complete' EXIT
case "${1:---help}" in --send) shift; do_send "$@" ;; --status) shift; do_status "$@" ;; --digest) shift; do_digest "$@" ;; --flush) shift; do_flush "$@" ;; --help) tool_help ;; *) handle_standard_command "$@" ;; esac
