#!/bin/sh -e

__cpu_freq_detail() {
  cat /proc/cpuinfo
}

__cpu_freq() {
  local hz freq count cores unit=""
  if [ -r "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq" ]; then
    # Linux
    cores=$(getconf _NPROCESSORS_ONLN 2>/dev/null)
    read hz < /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
    fpdiv $hz "1000000" 1 # 1Ghz
    freq="${_RET}"
    unit="GHz"
  elif [ -r "/proc/cpuinfo" ]; then
    # 他のLinux
    cores=$(getconf _NPROCESSORS_ONLN 2>/dev/null || grep -ci "^processor" /proc/cpuinfo)
    if egrep -q -s -i -m 1 "^cpu MHz|^clock" /proc/cpuinfo; then
      freq=$(egrep -i -m 1 "^cpu MHz|^clock" /proc/cpuinfo | awk -F"[:.]" '{ printf "%01.1f", $2 / 1000 }')
      unit="GHz"
    else
      freq=$(egrep -i -m 1 "^bogomips" /proc/cpuinfo | awk -F"[:.]" '{ print $2 }')
      freq=$(printf "%s %s" "$freq" "$count" | awk '{printf "%01.1f\n", $1/$2/1000}')
      unit="GHz"
    fi
  elif cores=$(sysctl -n hw.ncpuonline 2>/dev/null) && hz=$(sysctl -n hw.cpuspeed 2>/dev/null); then
    # OpenBSD
    if [ "$hz" -ge "1000" ]; then
      fpdiv $hz "1000" 1 # 1Ghz
      freq="${_RET}"
      unit="GHz"
    else
      freq="${hz}"
      unit="MHz"
    fi
  elif hz=$(sysctl -n dev.cpu.0.freq 2>/dev/null); then
    # FreeBSD
    cores=$(sysctl -n hw.ncpu 2>/dev/null)
    if [ "$hz" -ge "1000" ]; then
      fpdiv $hz "1000" 1 # 1Ghz
      freq="${_RET}"
      unit="GHz"
    else
      freq="${hz}"
      unit="MHz"
    fi
  elif cores=$(sysctl -n hw.ncpu 2>/dev/null) && hz=$(sysctl -n hw.cpufrequency | awk '{ printf "%.0f\n", $1 / 1000000 }' 2>/dev/null); then
    # macOS
    if [ "$hz" -ge "1000" ]; then
      fpdiv $hz "1000" 1 # 1Ghz
      freq="${_RET}"
      unit="GHz"
    else
      freq="${hz}"
      unit="MHz"
    fi
  fi

  [ -n "$freq" ] || return
  color c W; printf "%s" "${cores}x"; color b c W; printf "%s" "$freq"; color -; color c W; printf "%s" "$unit"; color --
}