// 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"

	offline  = "offline"
	online   = "online"
	possible = "possible"
	present  = "present"
)

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

func readCPURangeWith[ any]( string,  func( string) (, error)) (, error) {
	var  
	,  := os.ReadFile(filepath.Join(sysfsCPUBasePath, ))
	if  != nil {
		return , 
	}
	return (string())
}

func countCPURange( string) (int, error) {
	,  := listCPURange()
	return len(), 
}

func listCPURange( string) ([]int, error) {
	 = strings.Trim(, "\n ")

	// Treat empty file as valid. This might be the case if there are no offline CPUs in which
	// case /sys/devices/system/cpu/offline is empty.
	if  == "" {
		return []int{}, nil
	}

	var  []int
	for  := range strings.SplitSeq(, ",") {
		if  == "" {
			return nil, fmt.Errorf("empty CPU range in CPU string %q", )
		}
		, ,  := strings.Cut(, "-")
		,  := strconv.ParseUint(, 10, 32)
		if  != nil {
			return nil, 
		}
		if ! {
			// range containing a single element
			 = append(, int())
			continue
		}
		,  := strconv.ParseUint(, 10, 32)
		if  != nil {
			return nil, 
		}
		if  <  {
			return nil, fmt.Errorf("last CPU in range (%d) less than first (%d)", , )
		}
		for  := int();  <= int(); ++ {
			 = append(, )
		}
	}
	return , nil
}

func getConfigured() (int, error) {
	,  := os.ReadDir(sysfsCPUBasePath)
	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) {
	,  := os.ReadFile(filepath.Join(sysfsCPUBasePath, "kernel_max"))
	if  != nil {
		return 0, 
	}
	,  := strconv.ParseInt(strings.Trim(string(), "\n "), 10, 64)
	if  != nil {
		return 0, 
	}
	return int(), nil
}

func getOffline() (int, error) {
	return readCPURangeWith(offline, countCPURange)
}

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

func getPossible() (int, error) {
	return readCPURangeWith(possible, countCPURange)
}

func getPresent() (int, error) {
	return readCPURangeWith(present, countCPURange)
}

func listOffline() ([]int, error) {
	return readCPURangeWith(offline, listCPURange)
}

func listOnline() ([]int, error) {
	return readCPURangeWith(online, listCPURange)
}

func listPossible() ([]int, error) {
	return readCPURangeWith(possible, listCPURange)
}

func listPresent() ([]int, error) {
	return readCPURangeWith(present, listCPURange)
}