//go:build license
// +build license

package license

import (
	"encoding/pem"
	"fmt"
	"log"
	"os"
	"runtime"

	"starwiz.cn/sjy01/image-proc/license/public"
)

var ProductName = "sjy01-data-processing"

func VerifyLicense() {
	machineID, err := public.GetMachineID()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("machine ID:", machineID)
	fmt.Println("product name:", ProductName)

	if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
		fmt.Println("license is not required on this platform:", runtime.GOOS)
		return
	}

	value, err := public.LoadKey("license.lic")
	if err != nil {
		log.Println("invalid license", err)
		os.Exit(130)
	}

	var block *pem.Block
	if block, _ = pem.Decode(value); block == nil {
		fmt.Printf("%s\n", "license must be PEM")
		os.Exit(130)
	}

	l, err := public.BytesToLicense(string(block.Bytes))
	if err != nil {
		fmt.Println("invalid license", err)
		os.Exit(131)
	}

	if err := l.Valid(ProductName, machineID); err != nil {
		fmt.Println("invalid license", err)
		os.Exit(132)
	}
}
