package main

import (
	"container/list"
	"fmt"
	"github.com/md14454/gosensors"
	"os/exec"
	"strings"
	"time"
)

func main() {
	exec.Command("ipmitool", "raw", "0x30", "0x30", "0x01", "0x00")
	exec.Command("ipmitool", "raw", "0x30", "0x30", "0x02", "0xff", "1")
	gosensors.Init()
	defer gosensors.Cleanup()
	var lastPwm int64
	lastPwm = 1
	for {
		maxTemp := getMaxTemp()
		var result int64
		result = 0
		if maxTemp <= 34 {
			result = 0x1
		} else if maxTemp >= 60 {
			result = 0x30
		} else if maxTemp >= 58 {
			result = 0x1F
		} else if maxTemp >= 56 {
			result = 0x1A
		} else {
			result = 0x1 + int64((maxTemp-34)/2)
		}
		if lastPwm != result {
			execStrArg := fmt.Sprintf("%d", result)
			//fmt.Println(execStrArg)
			exec.Command("ipmitool", "raw", "0x30", "0x30", "0x02", "0xff", execStrArg)
			lastPwm = result
		}
		time.Sleep(time.Second)
	}
}

func getMaxTemp() float64 {
	var max float64
	max = -65535
	tempList := getPackageTemp()
	for e := tempList.Front(); e != nil; e = e.Next() {
		tmp := e.Value.(float64)
		if tmp > max {
			max = tmp
		}
	}
	return max
}

func getPackageTemp() *list.List {
	result := list.New()
	chips := gosensors.GetDetectedChips()
	for i := range chips {
		chip := chips[i]
		features := chip.GetFeatures()
		for j := range features {
			feature := features[j]
			if strings.Contains(feature.GetLabel(), "Package") {
				result.PushBack(feature.GetValue())
			}
		}
	}
	return result
}