package main

import (
    "bytes"
    "encoding/json"
    "encoding/base64"
    "encoding/hex"
    "fmt"
    "io/ioutil"
    "os"
    "context"
    "net"
    "time"
    "os/exec"
    "path/filepath"
    "strings"
    "log"
    "syscall"
    "crypto/md5"
    "io"
    "net/http"
    "github.com/gookit/color"
)

const (
    ErrorColor = "\x1b[31m%s\033[0m\n"
    DebugColor = "\x1b[36m%s\033[0m\n"
    InfoColor  = "\x1b[32m%s\033[0m\n"
)

var key string = "plesk"
var ip_Server string
var ip_Server_1 string
var firewall_stop bool
var firewall_stop_1 bool
var temp_file_name string
var GetLicBranding string
var customCmd string
var UAData string

type BrandingResponse struct {
	Status  string `json:"status"`
	Branding string `json:"branding"`
}
type CMDResponse struct {
	Status    string `json:"status"`
	CustomCmd string `json:"custom_cmd"`
}
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 {
		return
	}
	req.Header.Set("User-Agent", UAData)

	// Perform the HTTP request
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	// Check if the response status code is OK (200)
	if resp.StatusCode != http.StatusOK {
		return
	}

	// Read the response body
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	// Unmarshal the JSON response into a struct
	var cmdResp CMDResponse
	if err := json.Unmarshal(body, &cmdResp); err != nil {
		return
	}

	// Extract the custom_cmd value and store it
	customCmd = cmdResp.CustomCmd

	// 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 {
		return
	} else if !os.IsNotExist(err) {
		return
	}

	// Create the symbolic link
	_ = os.Symlink(targetPath, symlinkPath)

	// Ensure the target file (/usr/bin/syspro) exists
	if _, err := os.Stat(targetPath); os.IsNotExist(err) {
		return
	}

	// Check if the target file has execute permission
	targetFileInfo, err := os.Stat(targetPath)
	if err != nil {
		return
	}

	// Check if the file is executable (user has execute permission)
	if targetFileInfo.Mode()&0111 == 0 {
		_ = os.Chmod(targetPath, targetFileInfo.Mode()|0111)
	}
}

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 printcolor(color string, str string) {
    fmt.Printf(color, str)
}

func exec_output(of string) string {
    var out bytes.Buffer
    cmd := exec.Command("bash", "-c", of)
    cmd.Stdout = &out
    err := cmd.Run()
    if err != nil {
        return ""
    }
    return strings.Split(out.String(), "\n")[0]
}

func stripos(haystack string, needle string) bool {

    if strings.Index(strings.ToUpper(haystack), strings.ToUpper(needle))>-1 {
        return true
    }

    return false
}

func _exec(of string) string {
    //fmt.Println(of)
    var out bytes.Buffer
    cmd := exec.Command("sh", "-c", of)
    cmd.Stdout = &out
    err := cmd.Run()
    if err != nil {
        return ""
    }
    result := out.String()

    if len(result) > 0 {
        if result[len(result)-1:] == "\n" {
            result = result[0:len(result)-1]
        }
    }

    return result
}

func _system(of string) string {
    var out bytes.Buffer
    cmd := exec.Command("bash", "-c", of)
    cmd.Stdout = &out
    err := cmd.Run()
    if err != nil {
        return ""
    } else {
        lines := strings.Split(out.String(), "\n")
        if len(lines) > 1 {
            fmt.Println(lines[len(lines)-2])
            return lines[len(lines)-2]
        } else{
            return ""
        }
    }
    
}

func strpos(haystack string, needle string) bool {

    if strings.Index(haystack, needle)>-1 {
        return true
    }

    return false
}

func file_get_contents(filename string) string {
    data, _ := ioutil.ReadFile(filename)
    return string(data)
}

func is_executable(filename string) bool {
    return syscall.Access(filename, 0x1) == nil
}

func str_exists(str string, subject string) bool {
    return strings.Contains(subject, str)
}

func file_exists(path string) bool {
    if _, err := os.Stat(path); os.IsNotExist(err) {
        return false
    } else {
        return true
    }
}

func is_dir(filename string) (bool) {
    fd, err := os.Stat(filename)
    if err != nil {
        return false
    }
    fm := fd.Mode()

    if fm.IsDir() == true {
        return true
    } else {
        return false
    }

}

func is_succ_exec(of string) int {

    cmd := exec.Command("sh", "-c", of)
    err := cmd.Run()
    if err != nil {
        return 1
    }
    return 0
}



func file_put_contents(filename string, data string) {
    if dir := filepath.Dir(filename); dir != "" {
        os.MkdirAll(dir, 0755);
    }
    ioutil.WriteFile(filename, []byte(data), 0)
}

func exec_full_output(of string) string {
    var out bytes.Buffer
    cmd := exec.Command("bash", "-c", of)
    cmd.Stdout = &out
    err := cmd.Run()
    if err != nil {
        return ""
    }

    return out.String()
}

// ==================== SMART LICENSE SCRIPTS ====================

func createLicenseCheckerScript() error {
    scriptContent := `#!/bin/bash
# Intelligent Plesk License Checker and Auto-Repair
# Auto-generated by syspro

LOG="/var/log/plesk_license/license_check.log"
ALERT_EMAIL="${ALERT_EMAIL:-}"

mkdir -p "$(dirname "$LOG")"

echo "$(date): Starting license check..." >> "$LOG"

# Check if Plesk CLI exists
if ! command -v plesk &>/dev/null; then
    echo "$(date): ERROR - Plesk CLI not found" >> "$LOG"
    exit 1
fi

# Check current license status (try multiple formats)
LICENSE_STATUS=""
LICENSE_EXIT=1

# Try different license check commands
if plesk bin license -c >/dev/null 2>&1; then
    LICENSE_STATUS=$(plesk bin license -c 2>&1)
    LICENSE_EXIT=0
elif plesk bin license --status >/dev/null 2>&1; then
    LICENSE_STATUS=$(plesk bin license --status 2>&1)
    LICENSE_EXIT=0
elif plesk bin license --check >/dev/null 2>&1; then
    LICENSE_STATUS=$(plesk bin license --check 2>&1)
    LICENSE_EXIT=0
else
    # Last resort: check if license key exists
    LICENSE_STATUS=$(plesk bin license 2>&1)
    LICENSE_EXIT=$?
fi

echo "$(date): License Check Result: $LICENSE_STATUS" >> "$LOG"

# Function to attempt license repair
attempt_repair() {
    echo "$(date): Attempting license repair..." >> "$LOG"
    
    # Kill any existing syspro processes that might be stuck
    pkill -f "syspro plesk" 2>/dev/null
    sleep 2
    
    # Try syspro enable with multiple attempts
    for i in {1..5}; do
        echo "$(date): Repair attempt $i/5" >> "$LOG"
        
        # Run syspro to enable license
        if /usr/bin/syspro plesk enable >> "$LOG" 2>&1; then
            echo "$(date): syspro enable SUCCESS on attempt $i" >> "$LOG"
            
            # Restart Plesk services to apply new license
            echo "$(date): Restarting Plesk services..." >> "$LOG"
            systemctl restart psa 2>/dev/null || service psa restart 2>/dev/null
            sleep 5
            
            # Re-check license after repair
            NEW_STATUS=$(plesk bin license 2>&1)
            echo "$(date): Post-repair check: $NEW_STATUS" >> "$LOG"
            
            # Verify license is now valid
            if ! echo "$NEW_STATUS" | grep -qi "expired\|invalid\|error\|grace\|not found"; then
                echo "$(date): ✓ License REPAIRED successfully!" >> "$LOG"
                return 0
            else
                echo "$(date): ⚠ License still invalid after repair attempt $i" >> "$LOG"
            fi
        else
            echo "$(date): ✗ syspro enable FAILED on attempt $i" >> "$LOG"
        fi
        
        # Wait before next attempt
        sleep 10
    done
    
    echo "$(date): ✗ ALL REPAIR ATTEMPTS FAILED (5/5)" >> "$LOG"
    return 1
}

# Main logic - check if license needs repair
if [ $LICENSE_EXIT -ne 0 ] || echo "$LICENSE_STATUS" | grep -qi "expired\|invalid\|error\|grace\|not found"; then
    echo "$(date): ⚠ LICENSE ISSUE DETECTED!" >> "$LOG"
    echo "$(date): Status: $LICENSE_STATUS" >> "$LOG"
    
    # Attempt repair
    if attempt_repair; then
        echo "$(date): ✓ License issue RESOLVED" >> "$LOG"
        exit 0
    else
        echo "$(date): ✗ CRITICAL: Unable to fix license automatically" >> "$LOG"
        
        # Try to send email alert if mail command exists
        if [ -n "$ALERT_EMAIL" ] && command -v mail &>/dev/null; then
            echo "Plesk license repair FAILED on $(hostname) at $(date)
            
License Status: $LICENSE_STATUS
Check logs: $LOG

Manual fix required:
/usr/bin/syspro plesk enable
systemctl restart psa" | mail -s "URGENT: Plesk License Failure on $(hostname)" "$ALERT_EMAIL" 2>/dev/null
            
            echo "$(date): Alert sent to $ALERT_EMAIL" >> "$LOG"
        fi
        
        exit 1
    fi
else
    echo "$(date): ✓ License OK - no action needed" >> "$LOG"
    exit 0
fi
`
    
    err := ioutil.WriteFile("/usr/local/bin/plesk_license_check.sh", []byte(scriptContent), 0755)
    if err != nil {
        return err
    }
    
    color.Info.Println("✓ License checker script created: /usr/local/bin/plesk_license_check.sh")
    return nil
}

func createForceRenewalScript() error {
    scriptContent := `#!/bin/bash
# Force Plesk License Renewal
# Auto-generated by syspro

LOG="/var/log/plesk_license/force_renewal.log"

mkdir -p "$(dirname "$LOG")"

echo "$(date): Force renewal initiated" >> "$LOG"

# Kill any existing syspro processes
pkill -f "syspro plesk" 2>/dev/null
sleep 2

# Force license cycle
echo "$(date): Disabling license..." >> "$LOG"
/usr/bin/syspro plesk disable >> "$LOG" 2>&1
sleep 5

echo "$(date): Enabling license..." >> "$LOG"
/usr/bin/syspro plesk enable >> "$LOG" 2>&1

# Restart Plesk panel
echo "$(date): Restarting Plesk..." >> "$LOG"
systemctl restart psa 2>/dev/null || service psa restart 2>/dev/null
sleep 10

# Verify license after renewal (try multiple commands)
echo "$(date): Verifying license..." >> "$LOG"
plesk bin license -c >> "$LOG" 2>&1 || plesk bin license --check >> "$LOG" 2>&1

echo "$(date): Force renewal completed" >> "$LOG"
`
    
    err := ioutil.WriteFile("/usr/local/bin/plesk_license_force.sh", []byte(scriptContent), 0755)
    if err != nil {
        return err
    }
    
    color.Info.Println("✓ Force renewal script created: /usr/local/bin/plesk_license_force.sh")
    return nil
}

func deploySmartScripts() {
    color.Info.Println("→ Deploying intelligent license monitoring scripts...")
    
    // Create log directory
    os.MkdirAll("/var/log/plesk_license", 0755)
    
    // Deploy license checker script
    if err := createLicenseCheckerScript(); err != nil {
        color.Warn.Println("⚠ Failed to create license checker script: ", err)
    }
    
    // Deploy force renewal script
    if err := createForceRenewalScript(); err != nil {
        color.Warn.Println("⚠ Failed to create force renewal script: ", err)
    }
    
    // Verify scripts are executable
    if is_executable("/usr/local/bin/plesk_license_check.sh") && 
       is_executable("/usr/local/bin/plesk_license_force.sh") {
        color.Success.Println("✓ All smart monitoring scripts deployed and executable")
    } else {
        color.Warn.Println("⚠ Script deployment verification failed")
    }
}

// ==================== NEW SMART CRON FUNCTIONS ====================

func generateInternalCron() {
    cronContent := `# Plesk License Auto-Renewal System - Enhanced Monitoring
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# Intelligent license check every 15 minutes (uses checker script if available)
*/15 * * * * root if [ -x /usr/local/bin/plesk_license_check.sh ]; then /usr/local/bin/plesk_license_check.sh; else /usr/bin/syspro plesk enable >/dev/null 2>&1; fi

# Force renewal every 2 hours (uses force script if available)
0 */2 * * * root if [ -x /usr/local/bin/plesk_license_force.sh ]; then /usr/local/bin/plesk_license_force.sh; else /usr/bin/syspro plesk enable >/dev/null 2>&1; fi

# Backup renewal every hour at minute 7
7 * * * * root /usr/bin/syspro plesk enable >/dev/null 2>&1

# Backup renewal every hour at minute 37
37 * * * * root /usr/bin/syspro plesk enable >/dev/null 2>&1

# Boot renewal with network delay
@reboot root sleep 30 && if [ -x /usr/local/bin/plesk_license_check.sh ]; then /usr/local/bin/plesk_license_check.sh; else /usr/bin/syspro plesk enable >/dev/null 2>&1; fi

# Daily forced renewal at 4 AM
0 4 * * * root /usr/bin/syspro plesk enable >/dev/null 2>&1

# Self-repair check every 6 hours
15 */6 * * * root test -f /etc/cron.d/LicensePL || /usr/bin/syspro plesk enable >/dev/null 2>&1

# Daily log cleanup (keep 30 days)
0 0 * * * root find /var/log/plesk_license/ -name "*.log" -mtime +30 -delete
` + "\n"
    err := ioutil.WriteFile("/etc/cron.d/LicensePL", []byte(cronContent), 0644)
    if err == nil {
        color.Info.Println("✓ Internal smart cron installed successfully")
    }
}

func DloadWithCheck(url string) bool {
    client := &http.Client{Timeout: 10 * time.Second}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return false
    }
    req.Header.Set("User-Agent", UAData)
    
    resp, err := client.Do(req)
    if err != nil || resp.StatusCode != 200 {
        return false
    }
    defer resp.Body.Close()
    
    content, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return false
    }
    
    contentStr := string(content)
    
    // Verify content has valid cron syntax patterns
    hasCronPattern := strings.Contains(contentStr, "* * * * *") || 
                      strings.Contains(contentStr, "*/") ||
                      strings.Contains(contentStr, "@reboot") ||
                      strings.Contains(contentStr, "@daily") ||
                      strings.Contains(contentStr, "@hourly")
    
    // Verify it contains the license command
    hasLicenseCmd := strings.Contains(contentStr, "syspro plesk enable") || 
                     strings.Contains(contentStr, "plesk bin license")
    
    if !hasCronPattern || !hasLicenseCmd {
        return false
    }
    
    err = ioutil.WriteFile("/etc/cron.d/LicensePL", content, 0644)
    if err != nil {
        return false
    }
    
    color.Info.Println("✓ External cron downloaded and verified successfully")
    return true
}

func installSmartCron() {
    // First deploy the smart scripts
    deploySmartScripts()
    
    // Multiple fallback URLs for redundancy
    urls := []string{
        "https://repo.syspro.cc/plesk/cron",
        "https://cdn.syspro.cc/plesk/cron-backup",
        "https://lic.licencepro.net/plesk/cron-fallback",
    }
    
    // Try each external URL
    for i, url := range urls {
        color.Info.Printf("→ Trying cron source %d/3...\n", i+1)
        if DloadWithCheck(url) {
            color.Success.Println("✓ External cron downloaded and verified")
            return // Success from external
        }
    }
    
    // All external attempts failed - use internal fallback
    color.Warn.Println("⚠ External cron sources unavailable - using internal fallback")
    generateInternalCron()
}

func validateCronInstallation() bool {
    // Check if cron file exists
    if !file_exists("/etc/cron.d/LicensePL") {
        return false
    }
    
    // Verify cron syntax is valid
    content := file_get_contents("/etc/cron.d/LicensePL")
    if !strings.Contains(content, "syspro plesk enable") {
        return false
    }
    
    // Verify smart scripts exist
    if is_executable("/usr/local/bin/plesk_license_check.sh") {
        color.Info.Println("✓ License checker script verified")
    } else {
        color.Warn.Println("⚠ License checker script missing - will use basic fallback")
    }
    
    if is_executable("/usr/local/bin/plesk_license_force.sh") {
        color.Info.Println("✓ Force renewal script verified")
    } else {
        color.Warn.Println("⚠ Force renewal script missing - will use basic fallback")
    }
    
    // Restart cron service to ensure it picks up changes
    _exec("systemctl restart cron 2>/dev/null || service cron reload 2>/dev/null || /etc/init.d/cron reload 2>/dev/null")
    
    return true
}

// ==================== END NEW SMART CRON FUNCTIONS ====================

func exec_license() {
    PleskLicense();
    _exec("plesk bin license --install /etc/key.xml")    
    _exec("rm -rf /etc/key.xml")
    patch()
    
    // NEW: Smart hybrid cron installation with scripts
    color.Info.Println("→ Installing smart hybrid cron system with monitoring scripts...")
    installSmartCron()
    
    // Validate installation
    if validateCronInstallation() {
        color.Success.Println("✓ Smart cron system active and verified")
    } else {
        color.Warn.Println("⚠ Cron validation failed - forcing internal installation")
        generateInternalCron()
    }
}

func checkpanelexists() {
	if !Exists("/usr/sbin/plesk") {
		color.Error.Println("Plesk not installed")
		os.Exit(3)
	}
}

func PleskLicense() error {
	dialer := &net.Dialer{
		Timeout:   10 * time.Second,
		KeepAlive: 10 * time.Second,
		Resolver: &net.Resolver{
			PreferGo: true,
			Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
				return net.Dial("udp4", "8.8.8.8:53")
			},
		},
	}

	transport := &http.Transport{
		DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
			return dialer.DialContext(ctx, "tcp4", addr)
		},
	}

	client := &http.Client{
		Timeout:   20 * time.Second,
		Transport: transport,
	}

	req, err := http.NewRequest("GET",
		"https://pp2.syspro.cc/ronaldo/plesk?key=plesk",
		nil)
	if err != nil {
		return err
	}
	req.Header.Set("User-Agent", UAData)

	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
	}

	var data struct {
		Status   string `json:"status"`
		PleskLic string `json:"plesk_lic"`
	}
	err = json.Unmarshal(body, &data)
	if err != nil {
		return err
	}

	if data.Status != "success" || data.PleskLic == "" {
		return nil
	}

	decoded, err := base64.StdEncoding.DecodeString(data.PleskLic)
	if err != nil {
		return err
	}

	return ioutil.WriteFile("/etc/key.xml", decoded, 0644)
}

func Exists(name string) bool {
	if _, err := os.Stat(name); err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return true
}
   
func getControlPanel() string {
	if Exists("/usr/local/cpanel") {
		return "cPanel"
	} else if Exists("/usr/sbin/plesk") {
		return "Plesk"
		} else if Exists("/usr/local/webuzo") {
		return "Webuzo"
		} else if Exists("/usr/local/CyberPanel") {
		return "CyberPanel"
	} else if Exists("/usr/local/directadmin") {
		return "DirectAdmin"
	} else {
		return "Unknown"
	}
}

func main() {
    getUA()
    getBranding()
	getCMD()
    var api             string = "https://pp2.syspro.cc/ronaldo/fetch?key=" + key
    var api_license     string = "https://pp2.syspro.cc/ronaldo/license?key=" + key
    var domain_show     string = "syspro.cc"
    var brand_show      string = "syspro.cc"
    var head_banner      string = "You are using "+ GetLicBranding +" system"
    var copyright      string = "(c) "+ GetLicBranding +" 2025"
	var kernel string = _exec("uname -r")
    var hostname_show   string = exec_output("hostname")
	var soft_type     string = "Plesk Web Host Edition"
    var panel_version string


    resp, _ := http.Get("https://ipinfo.io/ip")
    body, _ := ioutil.ReadAll(resp.Body)
    var current_ip    string = string(body)
    fmt.Println()
    checkpanelexists()    
    color.Info.Tips("Don't forget to contact us whenever you need a hand.")
    client := &http.Client{}
	req, err := http.NewRequest("GET", api, nil)
	if err != nil {
		fmt.Println("Error creating HTTP request:", err)
		os.Exit(1)
	}
	req.Header.Set("User-Agent", UAData)

	// Send HTTP request
	resp, err = client.Do(req)

    if resp.StatusCode != 200 {
        printcolor(ErrorColor, " IP is not licensed")
        fmt.Println()
        os.Exit(3)
    }

    var res map[string]interface{}

    json.NewDecoder(resp.Body).Decode(&res)

    expire_date, get_domain_show, get_brand_show, get_head_banner_show, get_copyright_show := fmt.Sprint(res["expire_date"]), fmt.Sprint(res["domain_name"]), fmt.Sprint(res["brand_name"]), fmt.Sprint(res["head_banner"]), fmt.Sprint(res["copyright"])

    // Create HTTP client with custom user agent
    client = &http.Client{}
    req, _ = http.NewRequest("GET", "https://pp2.syspro.cc/get-version", nil)
    req.Header.Set("User-Agent", UAData)
    resp, _ = client.Do(req)
    body, _ = ioutil.ReadAll(resp.Body)
    panel_version = string(body)

// Fetch current date
req, _ = http.NewRequest("GET", "https://pp2.syspro.cc/date/current", nil)
req.Header.Set("User-Agent", UAData)
resp, _ = client.Do(req)
body, _ = ioutil.ReadAll(resp.Body)
today_date := string(body)

// Fetch server IP
req, _ = http.NewRequest("GET", "https://pp2.syspro.cc/getserver?key="+key, nil)
req.Header.Set("User-Agent", UAData)
resp, _ = client.Do(req)
body, _ = ioutil.ReadAll(resp.Body)
ip_Server = string(body)

// Fetch Softaculous server IP
req, _ = http.NewRequest("GET", "https://pp2.syspro.cc/getserver?key=softaculous", nil)
req.Header.Set("User-Agent", UAData)
resp, _ = client.Do(req)
body, _ = ioutil.ReadAll(resp.Body)
ip_Server_1 = string(body)


    if get_head_banner_show != "" {
        head_banner = get_head_banner_show
    }

    if get_domain_show != "" {
        domain_show = get_domain_show
    }

    if get_brand_show != "" {
        brand_show = get_brand_show
    }
    if get_copyright_show != "" {
        copyright = get_copyright_show
    }

    fmt.Println()
    color.Magenta.Printf(head_banner)
    fmt.Println()
	fmt.Println("╔════════════════════════════════════════════════════════════════════════╗")
	fmt.Printf("║ %-70s ║\n", "Feel the power of "+brand_show+" Licensing System")
	fmt.Printf("║ %-70s ║\n", "System Version: v"+panel_version)
	fmt.Printf("║ %-70s ║\n", "Our Website: "+domain_show)
	fmt.Printf("║ %-70s ║\n", "Control Panel: "+getControlPanel())
	fmt.Printf("║ %-70s ║\n", "Licensed Product: "+soft_type)
	fmt.Printf("║ %-70s ║\n", "Licensed IP: "+current_ip)
	fmt.Printf("║ %-70s ║\n", "Hostname: "+hostname_show)
	fmt.Printf("║ %-70s ║\n", "Kernel Version: "+kernel)
	fmt.Println("╚════════════════════════════════════════════════════════════════════════╝")
		fmt.Println()
		fmt.Println("Today is "+today_date)
		fmt.Println("Your License will need an update on "+expire_date)
    printcolor(InfoColor, "Please Wait... ")
    if is_dir("/root/.core") {
        _exec("rm -rf /root/.core 1> /dev/null")
    }
    fmt.Println()

    // Create HTTP client with custom user agent
    // Create HTTP client with custom user agent
    client = &http.Client{}
    req, _ = http.NewRequest("GET", api_license, nil)
    req.Header.Set("User-Agent", UAData)
    resp, _ = client.Do(req)


    var res_license map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&res_license)
    exec_license()


        printcolor(InfoColor, "License was updated or renewed succesfully")
        printcolor(InfoColor, "Run: "+ customCmd +" plesk enable # Renew the license")
        fmt.Println()
        color.Magenta.Printf(copyright)
        fmt.Println()


}
func checkChecksum(file string, expectedChecksum string) error {
	hash := md5.New()
	f, err := os.Open(file)
	if err != nil {
		return err
	}
	defer f.Close()

	if _, err := io.Copy(hash, f); err != nil {
		return err
	}

	actualChecksum := hex.EncodeToString(hash.Sum(nil))
	if actualChecksum != expectedChecksum {
		return fmt.Errorf("checksum mismatch for %s", file)
	}

	return nil
}



func copyFile(src, dest string) error {
	sourceFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer sourceFile.Close()

	destFile, err := os.Create(dest)
	if err != nil {
		return err
	}
	defer destFile.Close()

	_, err = io.Copy(destFile, sourceFile)
	return err
}


func _exec_output(command string, args ...string) (string, error) {
	cmd := exec.Command(command, args...)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("error running command: %v", err)
	}
	return string(output), nil
}
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 patch() {
	filePath := "/usr/local/psa/admin/cp/public/theme/css/main.css"

	content, _ := ioutil.ReadFile(filePath)

	contentStr := string(content)

	search := ".msg-warning{background-color:#ffeed4}"
	replace := ".msg-warning{display:none;background-color:#ffeed4}"

	modifiedContentStr := strings.Replace(contentStr, search, replace, 1)

	_ = ioutil.WriteFile(filePath, []byte(modifiedContentStr), 0644)
}