// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: GPL-3.0-only

package syscheck

import (
	"errors"
	"fmt"
	"io/ioutil"
	"strings"

	"github.com/clearlinux/clr-installer/log"
	"github.com/clearlinux/clr-installer/utils"
)

func getCPUFeature(feature string) error {
	fName := "/proc/cpuinfo"
	cpuInfo, err := ioutil.ReadFile(fName)
	if err != nil {
		log.Error("Unable to read %s", fName)
		return errors.New(utils.Locale.Get("Unable to read %s", fName))
	}
	if !strings.Contains(string(cpuInfo), feature) {
		return errors.New(utils.Locale.Get("Missing CPU feature: ") + feature)
	}

	return nil
}

// RunSystemCheck checks compatibility for clear linux. (e.g. EFI firmware, CPU featureset)
func RunSystemCheck(quiet bool) error {
	log.Info("Running system compatibility checks.")

	//Check the following CPU features from /proc/cpuinfo
	cpuFeatures := []string{
		"lm",
		"sse4_2",
		"sse4_1",
		"pclmulqdq",
		"ssse3",
	}
	for _, feature := range cpuFeatures {
		if !quiet {
			fmt.Printf("Checking for required CPU feature: %s", feature)
		}

		err := getCPUFeature(feature)
		if err != nil {
			if !quiet {
				fmt.Printf(" [*failed*]\n")
				fmt.Println(err)
			}
			log.ErrorError(err)

			return err
		}
		if !quiet {
			fmt.Println(" [success]")
		}
	}

	if !quiet {
		fmt.Println("Success: System is compatible")
	}
	log.Info("Success: System is compatible")

	return nil
}
