// Copyright 2018 Tobias Klauser
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package numcpus

import (
	
	
	
	
	

	
)

const sysfsCPUBasePath = "/sys/devices/system/cpu"

func getFromCPUAffinity() (int, error) {
	var  unix.CPUSet
	if  := unix.SchedGetaffinity(0, &);  != nil {
		return 0, 
	}
	return .Count(), nil
}

func readCPURange( string) (int, error) {
	,  := ioutil.ReadFile(filepath.Join(sysfsCPUBasePath, ))
	if  != nil {
		return 0, 
	}
	return parseCPURange(strings.Trim(string(), "\n "))
}

func parseCPURange( string) (int, error) {
	 := int(0)
	for ,  := range strings.Split(, ",") {
		if len() == 0 {
			continue
		}
		 := strings.SplitN(, "-", 2)
		,  := strconv.ParseUint([0], 10, 32)
		if  != nil {
			return 0, 
		}
		if len() == 1 {
			++
			continue
		}
		,  := strconv.ParseUint([1], 10, 32)
		if  != nil {
			return 0, 
		}
		 += int( -  + 1)
	}
	return , nil
}

func getConfigured() (int, error) {
	,  := os.Open(sysfsCPUBasePath)
	if  != nil {
		return 0, 
	}
	defer .Close()
	,  := .Readdir(-1)
	if  != nil {
		return 0, 
	}
	 := 0
	for ,  := range  {
		if  := .Name(); .IsDir() && strings.HasPrefix(, "cpu") {
			,  := strconv.ParseInt([3:], 10, 64)
			if  == nil {
				++
			}
		}
	}
	return , nil
}

func getKernelMax() (int, error) {
	,  := ioutil.ReadFile(filepath.Join(sysfsCPUBasePath, "kernel_max"))
	if  != nil {
		return 0, 
	}
	,  := strconv.ParseInt(strings.Trim(string(), "\n "), 10, 32)
	if  != nil {
		return 0, 
	}
	return int(), nil
}

func getOffline() (int, error) {
	return readCPURange("offline")
}

func getOnline() (int, error) {
	if ,  := getFromCPUAffinity();  == nil {
		return , nil
	}
	return readCPURange("online")
}

func getPossible() (int, error) {
	return readCPURange("possible")
}

func getPresent() (int, error) {
	return readCPURange("present")
}