#!/bin/bash
# Usage: getHostInfo.sh

get_general_info() {
    local os_pretty_name=$(grep "PRETTY_NAME" /etc/os-release 2>/dev/null | cut -d= -f2 | tr -d '"')
    
    [ -z "$os_pretty_name" ] && os_pretty_name="Unknown Linux"
    
    cat << EOF
{
    "OperatingSystemPrettyName": "$os_pretty_name"
}
EOF
}

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

if generalInfo=$(hostnamectl --json=pretty 2>/dev/null); then
    generalCommand="hostnamectl --json=pretty"
else
    generalInfo=$(get_general_info)
    generalCommand="custom function (hostnamectl fallback)"
fi

dockerInfo=$(docker version --format 'json' 2>/dev/null || echo '{"error": "Docker not available"}')
cpuInfo=$(lscpu --json 2>/dev/null || echo '{"error": "lscpu not available"}')
memorySizeGB=$(free --giga 2>/dev/null | awk '/^Mem:/ {print $2}' || echo "0")
memorySizeB=$((memorySizeGB * 1024 * 1024 * 1024))
memoryInfo="[{\"description\":\"System memory\",\"units\":\"bytes\",\"size\":${memorySizeB}}]"
diskInfo=$(lsblk --json 2>/dev/null || echo '{"error": "lsblk not available"}')

metadata="{\n \"date\":\"${date}\",\n \"generalCommand\":\"${generalCommand}\",\n \"dockerCommand\":\"docker version --format 'json'\",\n \"cpuCommand\":\"lscpu --json\",\n \"memoryCommand\":\"lshw -json -C memory 2>/dev/null\",\n \"diskCommand\":\"lsblk --json\"\n}"

hostInfo="{\n \"general\":${generalInfo},\n \"docker\":${dockerInfo},\n \"cpu\":${cpuInfo},\n \"memory\":${memoryInfo},\n \"disk\":${diskInfo},\n \"metadata\":${metadata}}"

printf "${hostInfo}" > hostInfo.json

echo "Host information collected and saved to hostInfo.json"