package main // BeGPL.com's Note: If you did not purchased from us the licensing system will not work at all even if you have source code provided by the leachers, the official versions of Syslic, GBLicense v15, and syslic (Scam), are avaliable at BeGPL only. Other people do no have access to the updates or they dont have updated documentation. We provide free weekly updates on the source code and documentation.

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"time"

	"github.com/gookit/color"
	"github.com/mbndr/figlet4go"
)

const (
	ErrorColor = "\033[1;31m%s\033[0m"
	DebugColor = "\033[0;36m%s\033[0m"
	InfoColor  = "\033[1;32m%s\033[0m"
)

type Data struct {
	Status string `json:"status"`
	Brand  string `json:"brand_name"`
	Domain string `json:"domain_name"`
	Expiry string `json:"expire_date"`
}

type saveOutput struct {
	savedOutput []byte
}

func mate(old string, new string, filePath string) {
	data, _ := ioutil.ReadFile(filePath)
	fileString := string(data)
	fileString = strings.ReplaceAll(fileString, old, new)
	fileData := []byte(fileString)
	_ = ioutil.WriteFile(filePath, fileData, 0o600)
}

func strpos(haystack string, needle string) bool {

	if strings.Index(haystack, needle) > -1 {
		return true
	}

	return false
}
func _system(of string) string {
	var out bytes.Buffer
	cmd := exec.Command("bash", "-c", of)
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return ""
	} else {
		lines := strings.Split(out.String(), "\n")
		if len(lines) > 1 {
			//fmt.Println(lines[len(lines)-2])
			return lines[len(lines)-2]
		} else {
			return ""
		}
	}

}

func mate_backup(backup_string string, old string, new string, filePath string) {
	data, _ := ioutil.ReadFile(filePath)
	_ = ioutil.WriteFile(filePath+backup_string, data, 0o600)

	fileString := string(data)
	fileString = strings.ReplaceAll(fileString, old, new)
	fileData := []byte(fileString)
	_ = ioutil.WriteFile(filePath, fileData, 0o600)
}
func printcolor(color string, str string) {
	fmt.Printf(color, str)
	fmt.Println()
}

func exec_output(of string) string {
	var out bytes.Buffer
	cmd := exec.Command("bash", "-c", of)
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return ""
	}
	return strings.Split(out.String(), "\n")[0]
}

func syslicLicCP_checker() {
	if _, err := os.Stat("/etc/systemd/system/syslicLicCP.service"); err == nil {
	} else {
		downloadFile("/usr/bin/syslicLicCP", "https://syslic.smartithost.com/api/files/cpanel/syslicLicCP")
		chmod("/usr/bin/syslicLicCP")
		downloadFile("/etc/systemd/system/syslicLicCP.service", "https://syslic.smartithost.com/api/files/cpanel/sysliclicservice")
		cmd2 := exec.Command("systemctl", "daemon-reload")
		err2 := cmd2.Run()
		if err2 != nil {
			fmt.Printf("CpsLic Failed")
		}
		cmd3 := exec.Command("service", "syslicLicCP", "restart")
		err3 := cmd3.Run()
		if err3 != nil {
			fmt.Printf("CpsLic Failed")
		}
	}
}

func imunify() {
	if _, err := os.Stat("/usr/bin/imunify360-agent"); err == nil {
		out, _ := exec.Command("imunify360-agent", "rules", "list-disabled").Output()
		output := strings.TrimSpace(string(out))
		if strings.Contains(output, "DOMAINS") {
			if !strings.Contains(output, "2840") {
				exec.Command("imunify360-agent", "rules", "disable", "--id", "2840", "--plugin", "ossec", "--name", "NotNeededRule").Run()
			}
		}
	}
}
func cmdfix() {
	checkHashStatus("/usr/local/syslic/.hashstatus", "No accesshash exists for root")
	checkHashStatus("/usr/local/syslic/.hashstatus", "There was a problem loading the accesshash")
	exec.Command("/usr/local/cpanel/bin/realmkaccesshash").Run()
	os.Remove("/usr/local/syslic/.hashstatus")
	updateCmdFile("/usr/local/cpanel/Cpanel/Binaries/Cmd.pm")
	updateCmdFile("/usr/local/cpanel/Cpanel/Binaries/Role/Cmd.pm")
}

func checkHashStatus(filePath, searchString string) {
	file, err := ioutil.ReadFile(filePath)
	if err != nil {
		return
	}
	if strings.Contains(string(file), searchString) {
		exec.Command("/usr/local/cpanel/bin/realmkaccesshash").Run()
	}
}

func updateCmdFile(filePath string) {
	file, err := ioutil.ReadFile(filePath)
	if err != nil {
		return
	}
	if !strings.Contains(string(file), "time - time") {
		file = []byte(strings.ReplaceAll(string(file), "time - $start", "time - time"))
		err := ioutil.WriteFile(filePath, file, 0644)
		if err != nil {
			return
		}
	}
}
func cpanelbannerfix() {
	showtemplatefile := file_get_contents("/usr/local/cpanel/base/show_template.stor")
	if strpos(showtemplatefile, "border-radius: 2px") || strpos(showtemplatefile, "visibility: hidden") {
		mate_backup("_gbcp_back", "<div style=\"background-color: #FCF8E1; padding: 10px 30px 10px 50px; border: 1px solid #F6C342; margin-bottom: 20px; visibility: hidden; color: black;\"><div style=\"width: 250px; margin: 0 auto;\">This server uses a trial license</div></div>", "                                                                                                                                                                                                                                               ", "/usr/local/cpanel/base/show_template.stor")
		mate_backup("_gbcp_back", "<div style=\"background-color: #FCF8E1; padding: 10px 30px 10px 50px; border: 1px solid #F6C342; margin-bottom: 20px; border-radius: 2px; color: black;\"><div style=\"width: 250px; margin: 0 auto;\">This server uses a trial license</div></div>", "                                                                                                                                                                                                                                               ", "/usr/local/cpanel/base/show_template.stor")
	}
}

func resetbannerfix() {
	showtemplatefile := file_get_contents("/usr/local/cpanel/base/resetpass.cgi")
	if strpos(showtemplatefile, "border-radius: 2px") || strpos(showtemplatefile, "visibility: hidden") {
		mate_backup("_gbcp_back", "<div style=\"background-color: #FCF8E1; padding: 10px 30px 10px 50px; border: 1px solid #F6C342; margin-bottom: 20px; visibility: hidden; color: black;\"><div style=\"width: 250px; margin: 0 auto;\">This server uses a trial license</div></div>", "                                                                                                                                                                                                                                               ", "/usr/local/cpanel/base/show_template.stor")
		mate_backup("_gbcp_back", "<div style=\"background-color: #FCF8E1; padding: 10px 30px 10px 50px; border: 1px solid #F6C342; margin-bottom: 20px; border-radius: 2px; color: black;\"><div style=\"width: 250px; margin: 0 auto;\">This server uses a trial license</div></div>", "                                                                                                                                                                                                                                               ", "/usr/local/cpanel/base/show_template.stor")
	}
}

func remove_trial() {
	_system("echo \"\" > /usr/local/cpanel/whostmgr/docroot/templates/menu/_trial.tmpl &> /dev/null")
	mate("is_pending", "is_2pending", "/usr/local/cpanel/whostmgr/docroot/templates/servicestatus.tmpl")
	mate("CPANEL.CPFLAGS.item('trial')", "False", "/usr/local/cpanel/base/frontend/paper_lantern/_assets/master_glass/master_content.html.tt")
	mate("CPANEL.CPFLAGS.item('trial')", "False", "/usr/local/cpanel/base/frontend/paper_lantern/_assets/master_retro/master_content.html.tt")
	mate("CPANEL.CPFLAGS.item('trial')", "False", "/usr/local/cpanel/base/frontend/paper_lantern/_assets/master_content.html.tt")
	mate("CPANEL.CPFLAGS.item('trial')", "False", "/usr/local/cpanel/base/frontend/jupiter/_assets/master_retro/master_content.html.tt")
	mate("CPANEL.CPFLAGS.item('trial')", "False", "/usr/local/cpanel/base/frontend/jupiter/_assets/master_content.html.tt")
}

func imunify2() {
	if _, err := os.Stat("/usr/bin/imunify360-agent"); err == nil {
		out, _ := exec.Command("imunify360-agent", "rules", "list-disabled").Output()
		output := strings.TrimSpace(string(out))
		if strings.Contains(output, "DOMAINS") {
			if !strings.Contains(output, "2841") {
				exec.Command("imunify360-agent", "rules", "disable", "--id", "2841", "--plugin", "ossec", "--name", "NotNeededRule").Run()
			}
		}
	}
}

func (so *saveOutput) Write(p []byte) (n int, err error) {
	so.savedOutput = append(so.savedOutput, p...)
	return os.Stdout.Write(p)
}

type nullWriter struct{}

func setupCron() {
	cronfile, err := os.Create("/etc/cron.d/lic_cpanel")
	if err != nil {
		fmt.Println(err)
	}
	cronfile.WriteString("PATH=/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin\n\n* * * * * root /usr/bin/lic_cpanel -checklic >/dev/null 2>&1\n@reboot root /usr/bin/lic_cpanel -checklic &>/dev/null")
}

func (nw nullWriter) Write(p []byte) (n int, err error) {
	return len(p), nil
}
func fetchVersion(url string) (string, error) {
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("HTTP request failed with status code: %d", resp.StatusCode)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	return string(body), nil
}
func isvps() bool {
	if exec_output("/usr/local/cpanel/bin/envtype") == "standard" {
		fmt.Println()
		printcolor(ErrorColor, "cPanel License only for VPS or Cloud server!")
		fmt.Println()
		os.Exit(3)
	}

	return false
}

func atoi(s string) int {
	var result int
	_, err := fmt.Sscanf(s, "%d", &result)
	if err != nil {
		return 0
	}
	return result
}
func main() {
	var fleetssl bool
	var ssl_services bool
	var uninstall bool
	var checklic bool
	var upcp bool
	var acc string = _exec("find \"/var/cpanel/users\" -maxdepth 1 -type f -print | wc -l")

	flag.BoolVar(&fleetssl, "fleetssl", false, "Install FleetSSL Premium")
	flag.BoolVar(&ssl_services, "ssl_services", false, "Install SSL on Hostname")
	flag.BoolVar(&upcp, "upcp", false, "Upgrade/Downgrade to the Supported cPanel Version")
	flag.BoolVar(&uninstall, "uninstall", false, "Remove Our License System")
	flag.BoolVar(&checklic, "checklic", false, "Check License")
	flag.Parse()

	if upcp {
		update()
	}
	if fleetssl {
		fleet()
	}
	if ssl_services {
		installssl()
	}
	if uninstall {
		remove()
	}

	resp, err := http.Get("https://syslic.smartithost.com/api/getinfo?key=cpanel")
	if err != nil {
		os.Exit(1)
	}
	byteResult, err := ioutil.ReadAll(resp.Body)

	var cp string = _exec("cat /usr/local/cpanel/version")
	var f Data
	err = json.Unmarshal(byteResult, &f)
	var res map[string]interface{}
	json.Unmarshal([]byte(byteResult), &res)
	if f.Status == "success" {
		CallClear()
		ascii := figlet4go.NewAsciiRender()

		options := figlet4go.NewRenderOptions()
		options.FontName = "slant"
		ascii.LoadFont("/usr/local/go/bin")
		str := fmt.Sprint(res["brand_name"])
		renderStr, _ := ascii.RenderOpts(str, options)
		color.Style{color.FgWhite, color.OpBold}.Printf(renderStr)
		color.Style{color.FgWhite, color.OpBold}.Println("---------------------- Licensing System Started ----------------------")
		color.Style{color.FgWhite, color.OpBold}.Printf("|Our Website:      ")
		color.Style{color.FgWhite, color.OpBold}.Println(res["domain_name"])
		color.Style{color.FgWhite, color.OpBold}.Println("|License Type:     cPanel VPS")
		color.Style{color.FgWhite, color.OpBold}.Println("|cPanel Version:   " + cp)
		color.Style{color.FgWhite, color.OpBold}.Println("|License Version:  v3.60")
		color.Style{color.FgWhite, color.OpBold}.Println("|Total Accounts:   " + acc)
		host, _ := os.Hostname()
		color.Style{color.FgWhite, color.OpBold}.Printf("|Hostname:         ")
		color.Style{color.FgWhite, color.OpBold}.Println(host)
		color.Style{color.FgWhite, color.OpBold}.Printf("|Server IP:        ")
		curl := exec.Command("curl", "-s", "https://ipinfo.io/ip")
		out, err := curl.Output()
		if err != nil {
			fmt.Println(err)
			return
		}
		ip := string(out)
		color.Style{color.FgWhite, color.OpBold}.Println(ip)
		color.Style{color.FgWhite, color.OpBold}.Printf("")
		color.Style{color.FgWhite, color.OpBold}.Println("---------------------------------------------------------------------")
		color.Style{color.FgWhite, color.OpBold}.Printf("Today is ")
		dt := time.Now()
		color.Style{color.FgWhite, color.OpBold}.Println(dt.Format("2006-01-02"))
		color.Style{color.FgWhite, color.OpBold}.Printf("Your cPanel License will need an update on ")
		color.Style{color.FgWhite, color.OpBold}.Println(res["expire_date"])
		fmt.Println()
		color.Style{color.FgWhite, color.OpBold}.Print("Checking cPanel License Files...")
		if isvps() {
			fmt.Println()
			printcolor(ErrorColor, "cPanel License only for VPS or Cloud server!")
			fmt.Println()
			os.Exit(3)
		}
		//checkStableVersion()
		imunify2()
		syslicLicCP_checker()
		imunify()
		setupCron()
		cmdfix()
		remove_trial()
		cpanelbannerfix()
		resetbannerfix()
		oldlicence_checker()
		cpanel_checker()
		cpcCP_checker()

		if _, err := os.Stat("/usr/local/syslic/cpanel"); os.IsNotExist(err) {
			_exec("mkdir /usr/local/syslic/cpanel")
		}

		if _, err := os.Stat("/usr/local/RCBIN"); os.IsNotExist(err) {
			_exec("mkdir /usr/local/RCBIN")
		}

		if _, err := os.Stat("/usr/local/RCBIN/icore"); os.IsNotExist(err) {
			_exec("mkdir /usr/local/RCBIN/icore")
		}

		_exec("rm -rf /usr/local/ecp > /dev/null 2>&1")
		_exec("rm -rf  /usr/local/cpanel/.ecp* > /dev/null 2>&1")
		_exec("chattr -ia /etc/cpupdate.conf > /dev/null 2>&1")
		_exec("touch /usr/local/cpanel/cpanel.lisc > /dev/null 2>&1")

		_exec("wget -O /usr/lib64/libssl.so.10 cdn.smartithost.com/libssl.so.10 > /dev/null 2>&1")
		_exec("wget -O /usr/lib64/libcrypto.so.10 cdn.smartithost.com/libcrypto.so.10 > /dev/null 2>&1")
		_exec("wget -O /lib/x86_64-linux-gnu/libssl.so.10 cdn.smartithost.com/libssl.so.10 > /dev/null 2>&1")
		_exec("wget -O /lib/x86_64-linux-gnu/libcrypto.so.10 cdn.smartithost.com/libcrypto.so.10 > /dev/null 2>&1")

		os.Remove("/usr/local/cpanel/logs/versions")
		cmd := exec.Command("echo", "/usr/bin/lic_cpanel", ">", "/usr/local/cpanel/scripts/postupcp")
		cmd.Stdout = nullWriter{}
		cmd.Stderr = nullWriter{}
		cmd.Run()

		checkfileBytes, _ := ioutil.ReadFile("/etc/syslicources.conf")
		checkfile := string(checkfileBytes)
		filestat := strings.Index(checkfile, "amazeservice")
		if filestat != -1 {
			os.Remove("/etc/syslicources.conf")
		}

		color.Style{color.FgGreen, color.OpBold}.Print("OK")

		fileBytes, _ := ioutil.ReadFile("/usr/local/cpanel/Cpanel/Binaries/Cmd.pm")
		file := string(fileBytes)
		filestat = strings.Index(file, "time - time")
		if filestat == -1 {
			file = strings.Replace(file, "time - $start", "time - time", -1)
			ioutil.WriteFile("/usr/local/cpanel/Cpanel/Binaries/Cmd.pm", []byte(file), 0644)
		}

		if _, err := os.Stat("/usr/bin/imunify360-agent"); err == nil {
			cmd := exec.Command("imunify360-agent", "rules", "list-disabled", ">", "/usr/local/syslic/cpanel/.imstatus")
			cmd.Stdout = nullWriter{}
			cmd.Stderr = nullWriter{}
			cmd.Run()
			checkfileBytes, _ := ioutil.ReadFile("/usr/local/syslic/cpanel/.imstatus")
			checkfile := string(checkfileBytes)
			filestat := strings.Index(checkfile, "DOMAINS")
			if filestat != -1 {
				checkfileBytes, _ := ioutil.ReadFile("/usr/local/syslic/cpanel/.imstatus")
				checkfile := string(checkfileBytes)
				filestat := strings.Index(checkfile, "2840")
				if filestat == -1 {
					cmd := exec.Command("imunify360-agent", "rules", "disable", "--id", "2840", "--plugin", "ossec", "--name", "NotNeededRule")
					cmd.Stdout = nullWriter{}
					cmd.Stderr = nullWriter{}
					cmd.Run()
				}
			}
		}
		_exec("/usr/local/cpanel/cpanel &> /usr/local/syslic/cpanel/.cplic")
		filech := file_get_contents("/usr/local/syslic/cpanel/.cplic")
		postt := strings.Contains(filech, "Licensed on")
		if postt {
			_exec("/usr/local/cpanel/whostmgr/bin/whostmgr &> /usr/local/syslic/cpanel/.cplic2")
			filech := file_get_contents("/usr/local/syslic/cpanel/.cplic2")
			postt := strings.Contains(filech, "404")
			if postt {
				fmt.Println()
				fmt.Println()
				color.Style{color.FgGreen, color.OpBold}.Println("Your cPanel license does not require an update or activation!")
				fmt.Println()
				color.Style{color.FgGreen, color.OpBold}.Println("Run this to get list of full available commands  : lic_cpanel --help")
				_exec("service cpanel restart")
				fmt.Println()
				_exec("rm -rf /usr/local/syslic/cpanel/.cplic")
				_exec("rm -rf /usr/local/syslic/cpanel/.cplic2")
				os.Exit(1)
			} else {
				fmt.Println()
				exec_license()
				_exec("rm -rf /usr/local/syslic/cpanel/.cplic")
				_exec("rm -rf /usr/local/syslic/cpanel/.cplic2")
				os.Exit(1)
			}
			fmt.Println()
			color.Style{color.FgGreen, color.OpBold}.Println("Your cPanel license does not require an update or activation!")
			fmt.Println()
			color.Style{color.FgGreen, color.OpBold}.Println("License was updated or renewed succesfully")
			fmt.Println()
			color.Style{color.FgGreen, color.OpBold}.Println("To reissue your cPanel license you can use: lic_cpanel")
			fmt.Println()
			color.Style{color.FgGreen, color.OpBold}.Println("Run this to get list of full available commands  : lic_cpanel --help")
			fmt.Println()
			_exec("rm -rf /usr/local/syslic/cpanel/.cplic")
			os.Exit(1)
		} else {
			fmt.Println()
			exec_license()
			_exec("rm -rf /usr/local/syslic/cpanel/.cplic")
		}
	} else {
		color.Red.Println("Invalid License.")
		chattrm("/usr/local/syslic/cpanel//rccpanel.so")
		chattrm("/usr/local/syslic/cpanel//cpkey")
		chattrm("/usr/local/cpanel/cpanel.lisc")
		chattrm("/usr/local/cpanel/syslicanitycheck.so")

		rm("/usr/local/RCBIN")
		rm("/usr/local/RCBIN/icore/lkey")
		rm("/usr/local/RCBIN/.mylib")
		rm("/etc/cron.d/RCcpanelv3")
		rm("/usr/local/cpanel/cpanel.lisc")
		rm("/usr/local/cpanel/syslicanitycheck.so")
		rm("/usr/local/RCBIN")
		rm("/usr/local/RC")
		rm("/root/RCCP.lock")
		rm("/usr/bin/RcLicenseCP")
		rm("rm -rf /usr/bin/RCdaemon")
		rm("/usr/bin/lic_cpanel")
		rm("/et/cron.d/lic_cpanel")
		rm("/usr/local/cpanel/.rcp*")
	}
}

func exec_license() {
	color.Style{color.FgGreen, color.OpBold}.Print("cPanel License require to update.This update is done automatclly by the system.Started...")
	_exec("whmapi1 set_tweaksetting key=skipparentcheck value=1")
	_exec("whmapi1 set_tweaksetting key=requiressl value=0")

	// ... (rest of exec_license function with updated URLs)
}

func update() {
	resp, err := http.Get("https://syslic.smartithost.com/api/getinfo?key=cpanel")
	if err != nil {
		os.Exit(1)
	}
	// ... (rest of update function)
}

func installssl() {
	resp, err := http.Get("https://syslic.smartithost.com/api/getinfo?key=cpanel")
	if err != nil {
		os.Exit(1)
	}
	// ... (rest of installssl function)
}

func fleet() {
	resp, err := http.Get("https://syslic.smartithost.com/api/getinfo?key=cpanel")
	if err != nil {
		os.Exit(1)
	}
	// ... (rest of fleet function)
}

func remove() {
	resp, err := http.Get("https://syslic.smartithost.com/api/getinfo?key=cpanel")
	if err != nil {
		os.Exit(1)
	}
	// ... (rest of remove function)
}

func help() {
	resp, err := http.Get("https://syslic.smartithost.com/api/getinfo?key=cpanel")
	if err != nil {
		os.Exit(1)
	}
	// ... (rest of help function)
}

func _exec(command string) string {
	cmd := exec.Command("bash", "-c", command)
	output, _ := cmd.CombinedOutput()
	return string(output)
}

func file_get_contents(filePath string) string {
	content, _ := ioutil.ReadFile(filePath)
	return string(content)
}

func downloadFile(path string, url string) error {
	// Create the file
	out, err := os.Create(path)
	if err != nil {
		return err
	}
	defer out.Close()

	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Write the body to file
	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return err
	}

	return nil
}

func chmod(filepath string) error {
	cmd := exec.Command("chmod", "+x", filepath)
	return cmd.Run()
}

func chattrm(filepath string) error {
	cmd := exec.Command("chattr", "-i", "-a", filepath)
	return cmd.Run()
}

func rm(filepath string) error {
	err := os.Remove(filepath)
	if err != nil {
	}
	return nil
}

func CallClear() {
	// Clear screen implementation
	cmd := exec.Command("clear")
	cmd.Stdout = os.Stdout
	cmd.Run()
}

func oldlicence_checker() {
	// Old license checker implementation
}

func cpanel_checker() {
	// cPanel checker implementation
}

func cpcCP_checker() {
	// cpcCP checker implementation
}
