#!/usr/bin/env bash
set -u

role="${ROLE:-unknown}"

section() {
  printf '\n## %s\n' "$1"
}

run_if_available() {
  command_name="$1"
  shift
  if command -v "$command_name" >/dev/null 2>&1; then
    "$command_name" "$@" 2>&1 || true
  else
    printf '%s: not installed\n' "$command_name"
  fi
}

printf '# Sifangda server baseline\n'
printf 'role=%s\n' "$role"
printf 'collected_at=%s\n' "$(date -Iseconds 2>/dev/null || date)"

section "Identity"
hostname 2>&1 || true
id 2>&1 || true
uname -a 2>&1 || true
test -f /etc/os-release && sed -n '1,30p' /etc/os-release

section "CPU and memory"
run_if_available lscpu
run_if_available free -h
run_if_available swapon --show

section "Disk and filesystem"
run_if_available lsblk -f
run_if_available df -hT
run_if_available mount

section "Network"
run_if_available ip -br addr
run_if_available ip route
run_if_available ss -lntup

section "Time"
run_if_available timedatectl
run_if_available chronyc tracking

section "Security controls"
run_if_available getenforce
run_if_available firewall-cmd --state
run_if_available firewall-cmd --list-all

section "Installed runtime"
run_if_available nginx -v
test -x /usr/local/php7.3/bin/php && /usr/local/php7.3/bin/php -v 2>&1
test -x /usr/local/php/bin/php && /usr/local/php/bin/php -v 2>&1
test -L /usr/local/php/bin/php && printf 'php73_compat_link=%s\n' "$(readlink /usr/local/php/bin/php)"
test -x /usr/local/php7.4/bin/php && /usr/local/php7.4/bin/php -v 2>&1
run_if_available redis-server --version
run_if_available mysql --version
run_if_available supervisord --version

section "Service state"
for service_name in nginx php-fpm php-fpm7.4 redis mysql mysqld supervisor; do
  if command -v systemctl >/dev/null 2>&1; then
    systemctl is-enabled "$service_name" 2>&1 || true
    systemctl is-active "$service_name" 2>&1 || true
  fi
done

section "Conclusion"
printf 'This script is read-only. Review the output before any installation or configuration change.\n'
