#!/bin/bash

# --- Terminal Compatibility Fix ---
[[ -t 0 ]] && stty erase ^H 2>/dev/null || stty erase ^? 2>/dev/null

# --- Configuration ---
EMAIL="amin.uzan@gmail.com"
WEB_ROOT="/var/www/html"
CDN_URL="https://archive.cdnweb.info/installer"

# Colors
CYAN='\033[0;36m'
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
MAGENTA='\033[0;35m'
NC='\033[0m'

# Ensure root
if [ "$EUID" -ne 0 ]; then 
  echo -e "${RED}Please run as root or with sudo${NC}"
  exit 1
fi

# --- UI Helpers ---

header() {
    clear
    echo -e "${MAGENTA}┌──────────────────────────────────────────────────┐${NC}"
    echo -e "${MAGENTA}│${NC}          🚀 ${CYAN}WEB MANAGER v6.2 (SEO UPDATE)${NC}      ${MAGENTA}│${NC}"
    echo -e "${MAGENTA}└──────────────────────────────────────────────────┘${NC}"
}

get_domains() {
    mapfile -t domains < <(ls -d "${WEB_ROOT}"/*/ 2>/dev/null | xargs -n 1 basename)
}

cleanup_dir() {
    local dir=$1
    if [ -d "$dir" ] && [ "$(ls -A "$dir")" ]; then
        echo -e "${YELLOW}>> Wiping existing files in: $dir${NC}"
        rm -rf "${dir:?}"/*
        rm -rf "${dir:?}"/.[!.]*
    fi
}

# --- Logic Functions ---

modify_meta_flow() {
    header
    get_domains
    if [ ${#domains[@]} -eq 0 ]; then 
        echo -e "${RED}No domains found.${NC}"; read -p "Press enter..."; return
    fi

    echo -e "${YELLOW}SELECT DOMAINS TO MODIFY META (e.g., 1,3):${NC}"
    for i in "${!domains[@]}"; do
        echo -e "${CYAN}$((i+1)))${NC} ${domains[$i]}"
    done
    echo -n "Enter numbers: "
    read selections
    if [ -z "$selections" ]; then return; fi

    echo -e "\n${CYAN}Enter NEW Google Verification Code:${NC}"
    read g_code
    echo -e "${CYAN}Enter NEW Bing Verification Code:${NC}"
    read b_code

    IFS=',' read -ra ADDR <<< "$selections"
    for sel in "${ADDR[@]}"; do
        index=$((sel-1))
        if [[ -n "${domains[$index]}" ]]; then
            dom="${domains[$index]}"
            target_dir="$WEB_ROOT/$dom"
            index_file="$target_dir/index.html"

            if [ -f "$index_file" ]; then
                echo -e "${YELLOW}>> Updating $dom/index.html...${NC}"
                
                # --- Google Meta Pattern Logic ---
                if [ -n "$g_code" ]; then
                    # Check if the tag already exists
                    if grep -q "google-site-verification" "$index_file"; then
                        # Pattern: Replace content inside the existing tag
                        sed -i "s|meta name=\"google-site-verification\" content=\"[^\"]*\"|meta name=\"google-site-verification\" content=\"$g_code\"|g" "$index_file"
                    else
                        # Fallback: Replace the placeholder if it's still there
                        sed -i "s|\[google_code\]|$g_code|g" "$index_file"
                    fi
                    echo -e "${GREEN}  ✔ Google Meta Updated (Pattern Match)${NC}"
                fi

                # --- Bing Meta Pattern Logic ---
                if [ -n "$b_code" ]; then
                    if grep -q "msvalidate.01" "$index_file"; then
                        # Pattern: Replace content inside the existing Bing tag
                        sed -i "s|meta name=\"msvalidate.01\" content=\"[^\"]*\"|meta name=\"msvalidate.01\" content=\"$b_code\"|g" "$index_file"
                    else
                        # Fallback
                        sed -i "s|\[bing_code\]|$b_code|g" "$index_file"
                    fi
                    echo -e "${GREEN}  ✔ Bing Meta Updated (Pattern Match)${NC}"
                fi
            else
                echo -e "${RED}  ✘ index.html not found in $dom${NC}"
            fi
        fi
    done
    read -p "Meta Modification Finished. Press enter..."
}

deploy_html_site() {
    header; get_domains
    if [ ${#domains[@]} -eq 0 ]; then echo -e "${RED}No domains found.${NC}"; read -p "Press enter..."; return; fi

    echo -e "${YELLOW}SELECT DOMAINS TO DEPLOY HTML (e.g., 1,3):${NC}"
    for i in "${!domains[@]}"; do echo -e "${CYAN}$((i+1)))${NC} ${domains[$i]}"; done
    echo -n "Enter numbers: "
    read selections
    if [ -z "$selections" ]; then return; fi

    echo -n "Enter ZIP URL: "
    read zip_url
    if [ -z "$zip_url" ]; then return; fi

    IFS=',' read -ra ADDR <<< "$selections"
    for sel in "${ADDR[@]}"; do
        index=$((sel-1))
        if [[ -n "${domains[$index]}" ]]; then
            target_domain="${domains[$index]}"
            target_dir="$WEB_ROOT/$target_domain"
            echo -e "\n${CYAN}🌐 Processing $target_domain...${NC}"
            cleanup_dir "$target_dir"
            wget -q "$zip_url" -O "$target_dir/master.zip"
            if [ $? -eq 0 ]; then
                unzip -qo "$target_dir/master.zip" -d "$target_dir"
                rm "$target_dir/master.zip" 
                find "$target_dir" -type f -name "*.xml" -exec sed -i "s|\[url_website\]|https://$target_domain|g" {} +
                find "$target_dir" -type f -name "robots.txt" -exec sed -i "s|\[url_website\]|https://$target_domain|g" {} +
                chown -R www-data:www-data "$target_dir"
                find "$target_dir" -type d -exec chmod 755 {} \;
                find "$target_dir" -type f -exec chmod 644 {} \;
                echo -e "${GREEN}✔ Successfully deployed to $target_domain${NC}"
            else
                echo -e "${RED}✘ Download failed.${NC}"; rm -f "$target_dir/master.zip"
            fi
        fi
    done
    read -p "Finished. Press enter..."
}

add_domain_flow() {
    local ssl=$1
    header
    echo -e "${YELLOW}Bulk Add Domains (e.g. site1.com, site2.com):${NC}"
    read input
    if [ -z "$input" ]; then return; fi
    IFS=',' read -ra ADDR <<< "$input"
    for domain in "${ADDR[@]}"; do
        domain=$(echo $domain | xargs)
        echo -e "\n${CYAN}⚙️  Configuring: $domain...${NC}"
        mkdir -p "$WEB_ROOT/$domain"
        vhost_file="/etc/apache2/sites-available/$domain.conf"
        cat > "$vhost_file" <<EOF
<VirtualHost *:80>
    ServerName $domain
    ServerAlias www.$domain
    DocumentRoot $WEB_ROOT/$domain
    <Directory $WEB_ROOT/$domain>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
EOF
        a2ensite "$domain.conf" > /dev/null
        if [ "$ssl" = true ]; then
            certbot --apache -d "$domain" -d "www.$domain" --agree-tos -m "$EMAIL" --no-eff-email --redirect
        fi
        echo -e "${GREEN}✔ Domain $domain is now active.${NC}"
    done
    systemctl reload apache2
    read -p "Bulk Creation Complete. Press enter..."
}

install_script_flow() {
    header; get_domains

    if [ ${#domains[@]} -eq 0 ]; then 
        echo -e "${RED}No domains found.${NC}"
        read -p "Press enter..."
        return
    fi

    echo -e "${YELLOW}1) WP | 2) CMS Lite | 3) Micro Niche${NC}"
    read -p "Choice: " script_opt

    case $script_opt in 
        1) zip_file="wp.zip" ;; 
        2) zip_file="cmslite.zip" ;; 
        3) zip_file="microniche.zip" ;; 
        *) return ;; 
    esac

    header

    for i in "${!domains[@]}"; do 
        echo -e "${CYAN}$((i+1)))${NC} ${domains[$i]}"
    done

    read -p "Numbers (e.g., 1,2,3): " selections
    IFS=',' read -ra ADDR <<< "$selections"

    for sel in "${ADDR[@]}"; do
        index=$((sel-1))
        
        if [[ -n "${domains[$index]}" ]]; then
            target_domain="${domains[$index]}"
            target_dir="$WEB_ROOT/$target_domain"

            echo -e "${YELLOW}Processing $target_domain...${NC}"

            cleanup_dir "$target_dir"
            wget -q "$CDN_URL/$zip_file" -O "$target_dir/package.zip"
            unzip -qo "$target_dir/package.zip" -d "$target_dir"
            rm "$target_dir/package.zip"
            chown -R www-data:www-data "$target_dir"

            # --- LOGIKA AUTO-CRON UNTUK WORDPRESS ---
            if [ "$script_opt" == "1" ]; then
                # Definisikan command cron menggunakan path dinamis
                CRON_CMD="* * * * * php $target_dir/wp-cron.php > /dev/null 2>&1"
                
                # Masukkan ke crontab www-data (grep -Fv digunakan agar tidak ada cron duplikat jika di-install ulang)
                (crontab -u www-data -l 2>/dev/null | grep -Fv "$target_dir/wp-cron.php"; echo "$CRON_CMD") | crontab -u www-data -
                
                echo -e "${GREEN}✔ Auto WP-Cron added for $target_domain.${NC}"
            fi
            # ----------------------------------------

            echo -e "${GREEN}✔ Done installing on $target_domain.${NC}\n"
        fi
    done

    read -p "Finished. Press enter..."
}

delete_domain_flow() {
    header; get_domains
    if [ ${#domains[@]} -eq 0 ]; then read -p "No domains. Press enter..."; return; fi
    for i in "${!domains[@]}"; do echo -e "${CYAN}$((i+1)))${NC} ${domains[$i]}"; done
    read -p "Select numbers to DELETE: " selections
    read -p "Are you sure? (y/n): " confirm
    [[ ! "$confirm" =~ ^([yY])$ ]] && return
    IFS=',' read -ra ADDR <<< "$selections"
    for sel in "${ADDR[@]}"; do
        index=$((sel-1))
        dom="${domains[$index]}"
        echo -e "${RED}>> Removing $dom...${NC}"
        a2dissite "$dom.conf" &>/dev/null
        rm -rf "$WEB_ROOT/$dom"
        rm -f "/etc/apache2/sites-available/$dom.conf"
    done
    systemctl reload apache2
    read -p "Deletions complete. Press enter..."
}

# --- Main Loop ---

while true; do
    header
    echo -e " ${CYAN}1.${NC} Bulk Add Domain (Vhost Only)"
    echo -e " ${CYAN}2.${NC} Bulk Add Domain + SSL"
    echo -e " ${YELLOW}3. Deploy HTML Site${NC}"
    echo -e " ${YELLOW}4. Bulk Install Script${NC}"
    echo -e " ${MAGENTA}5. Modify Meta (SEO Verification)${NC}"
    echo -e " ${RED}6. Bulk Delete Domain${NC}"
    echo -e " ${NC}7. Exit"
    echo "────────────────────────────────────────────────────"
    echo -n "Choice: "
    read opt
    case $opt in
        1) add_domain_flow false ;;
        2) add_domain_flow true ;;
        3) deploy_html_site ;;
        4) install_script_flow ;;
        5) modify_meta_flow ;;
        6) delete_domain_flow ;;
        7) echo "Goodbye!"; exit 0 ;;
    esac
done