#!/bin/bash

# Colors for output
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
RED="\033[0;31m"
BLUE="\033[0;34m"
NC="\033[0m"

# Define constants
T4S_PATH="/usr/local/bin/t4s"
VERSION="1.2.0"
LOG_FILE="/var/log/t4s_install.log"

# Spinner function for progress indication
spinner() {
    local pid=$1
    local delay=0.1
    local spinstr='|/-\'
    while [ -d /proc/$pid ]; do
        local temp=${spinstr#?}
        printf " [%c]  " "$spinstr"
        spinstr=$temp${spinstr%"$temp"}
        sleep $delay
        printf "\b\b\b\b\b\b"
    done
    printf "    \b\b\b\b"
}

# Logging function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

# Check for sudo privileges
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}This script must be run as root. Please use sudo.${NC}"
    exit 1
fi

# Create log directory if it doesn't exist
mkdir -p "$(dirname "$LOG_FILE")" &>/dev/null
log "Starting Theme4Sell installation script v$VERSION"

# Header display
clear
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}    Theme4Sell Installation Script     ${NC}"
echo -e "${BLUE}           Version $VERSION            ${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Remove old file if it exists
if [ -f "$T4S_PATH" ]; then
    echo -e "${YELLOW}Removing previous Theme4Sell installation...${NC}"
    rm -f "$T4S_PATH" &>/dev/null &
    spinner $!
    log "Removed existing Theme4Sell script"
fi

# Create directory if it doesn't exist
echo -e "${YELLOW}Preparing installation directory...${NC}"
mkdir -p /usr/local/bin &>/dev/null &
spinner $!
log "Created installation directory /usr/local/bin"

# Download new script
echo -e "${YELLOW}Downloading Theme4Sell script...${NC}"
curl -s -o "$T4S_PATH" "https://script.theme4sell.com/t4s" &>/dev/null &
pid=$!
spinner $pid
wait $pid
if [ $? -eq 0 ]; then
    echo -e "${GREEN}Download completed successfully${NC}"
    log "Successfully downloaded Theme4Sell script"
else
    echo -e "${RED}Failed to download Theme4Sell script. Please try again later.${NC}"
    log "Error: Failed to download Theme4Sell script"
    exit 1
fi

# Set executable permissions
echo -e "${YELLOW}Setting permissions...${NC}"
chmod +x "$T4S_PATH" &>/dev/null &
spinner $!
log "Set executable permissions for $T4S_PATH"

# Verify installation
if [ -x "$T4S_PATH" ]; then
    # Add cron job only if not already present
    if ! crontab -l 2>/dev/null | grep -q "/usr/local/bin/t4s flush"; then
        (crontab -l 2>/dev/null; echo "@reboot /usr/local/bin/t4s flush > /dev/null 2>&1") | crontab -
        log "Added @reboot cron job for t4s flush"
    else
        log "Cron job for t4s flush already exists, skipping"
    fi

    echo -e "${GREEN}Verification complete: Theme4Sell script installed successfully${NC}"
    log "Installation verified successfully"
else
    echo -e "${RED}Installation verification failed. Please check the logs at $LOG_FILE${NC}"
    log "Error: Installation verification failed"
    exit 1
fi

# Final output
clear
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}    Theme4Sell Installation Complete    ${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "${BLUE}Thank you for installing Theme4Sell v$VERSION!${NC}"
echo -e "${BLUE}You can now use the 't4s' command to access the system.${NC}"
echo -e "${BLUE}Logs are available at: $LOG_FILE${NC}"
echo ""
echo -e "${YELLOW}Usage Guide:${NC}"
echo -e "  ${GREEN}t4s${NC}                 → Launch main menu"
echo -e "  ${GREEN}t4s update${NC}          → Update Theme4Sell to latest version"
echo -e "  ${GREEN}t4s tweak${NC}           → Apply cPanel tweak settings"
echo -e "  ${GREEN}t4s install-csf${NC}     → Install CSF firewall"
echo ""
echo -e "  ${GREEN}t4s tools${NC}           → Run Tools script"
echo -e "  ${GREEN}t4s rc${NC}              → Run RC licensing system"
echo -e "  ${GREEN}t4s rc-renew${NC}        → Renew RC license"
echo -e "  ${GREEN}t4s syslic${NC}          → Run Syslic licensing system"
echo -e "  ${GREEN}t4s syslic-renew${NC}    → Renew Syslic license"
echo ""
echo -e "  ${GREEN}t4s whitelist <ip>${NC} → Whitelist IP/domain"
echo -e "  ${GREEN}t4s allow <ip>${NC}     → Whitelist IP/domain"
echo -e "  ${GREEN}t4s blacklist <ip>${NC} → Blacklist IP/domain"
echo -e "  ${GREEN}t4s block <ip>${NC}     → Blacklist IP/domain"
echo -e "  ${GREEN}t4s delete <ip>${NC}    → Remove IP/domain from firewall"
echo -e "  ${GREEN}t4s flush${NC}           → Reset firewall rules"
echo -e "  ${GREEN}t4s resolve${NC}         → Resolve DNS"
echo ""
echo -e "${BLUE}For more details, run: t4s${NC}"
echo ""
log "Theme4Sell installation completed"