echo "Starting HW Discovery"

function cpu_cores() {
  hwinfo --cpu | grep -c "Hardware Class: cpu"
}

function ram() {
  # XXX: /proc may not be the best place to get this from, but hwinfo reports weird values (e.g. "1GB + 512MB" on a test VM of mine)
  _KB=$(grep MemTotal /proc/meminfo | awk '{ print $2 }')
  echo "$((_KB * 1024)) bytes"
}

function pxe_mac() {
  # XXX: This is making all sorts of risky assumptions. Firstly that the underlying drivers correctly report link. Secondly that only the primary
  # XXX: NIC is wired up. Without a backend service on the DHCP/PXE server which could examine all of our detected MACs, there really is no good
  # XXX: way to solve this in Linux.
  _info1=$(hwinfo --network|grep -B2 "Link detected: yes"|grep -C1 "HW Address:")
  _info2=$(echo "${_info1}"|awk '/Device File: (vlan*|br*)/{for(x=NR-2;x<=NR+2;x++)d[x];}{a[NR]=$0}END{for(i=1;i<=NR;i++)if(!(i in d))print a[i]}')
  _dev=$(echo "${_info1}" | grep "Device File:"|awk -F':' {'print $2'}|tr -d ' ')
  _mac=$(echo "${_info2}" | grep "HW Address:"|awk -F'ss:' {'print $2'}|tr -d ' ')
  echo $_mac
  export HW_DISCOVERY_BOOT_IFACE="$_mac"
}

function disk() {
  # XXX: This is returning only the first disk discovered, which is very likely to be insufficient on machines that present us with multiple disks
  # XXX: This is likely reporting in TB, but the units are not guaranteed. Maybe convert to bytes?
  lshw -C disk | grep size | awk -F'(' '{ print $2 }' | tr -d ')' | head -1
}

function raw_disk() {
  hwinfo --disk
}

function raw_network() {
  hwinfo --network
}

HW_DISCOVERY_OUTPUT=$(cat <<EOF
{
  "cpu cores" : "$(cpu_cores)",
  "disk size" : "$(disk)",
  "ram size" : "$(ram)",
  "pxe mac" : "$(pxe_mac)",
  "extra data" : {
    "raw disk" : "$(raw_disk | base64)",
    "raw network" : "$(raw_network | base64)",
    $_vendor_hwdiscovery_data
  }
}
EOF
)

# Print the resulting JSON for debugging purposes
echo $HW_DISCOVERY_OUTPUT

# Now submit the JSON
HW_DISCOVERY_DATA=$(echo ${HW_DISCOVERY_OUTPUT} | base64)
HW_DISCOVERY_URL=$(get_kernel_parameter HW_DISCOVERY_URL)
wget --post-data "hwdiscovery=true&hwdiscovery_data=${HW_DISCOVERY_DATA}" ${HW_DISCOVERY_URL}

sleep 30

