#!/bin/bash

perform_x86_teamviewer_operation() {
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        echo "Please run this script as root."
        exit
    fi

    echo "Starting TeamViewer installation and EDID configuration..."

    # Check if unzip is installed
    if ! command -v unzip &> /dev/null; then
        echo "Unzip not found. Installing unzip..."
        apt-get update -y && apt-get install -y unzip
        if [ $? -ne 0 ]; then
            echo "Failed to install unzip. Please check your package manager."
            exit 1
        fi
    fi

    # Modify /usr/bin/smgstats file: remove # from a specific line and add # if not present
    SMGSTATS_FILE="/usr/bin/smgstats"
    if [ -f "$SMGSTATS_FILE" ]; then
        # Remove # from the Teamviewer ID line
        sed -i '/#echo "Teamviewer ID = $(sudo teamviewer info|grep "TeamViewer ID"|awk '\''{print $5}'\'')"/s/^#//' "$SMGSTATS_FILE"
        
        # Add # to the Zerotier line if not present
        if grep -q '^echo "Zerotier = $(sudo zerotier-cli info)"' "$SMGSTATS_FILE"; then
            sed -i '/^echo "Zerotier = $(sudo zerotier-cli info)"/s/^/#/' "$SMGSTATS_FILE"
        fi
    fi

    # Define URLs and file paths
    EDID_ZIP_URL="https://install.smg.com.tr/AIOSetup/edid_1024x768.zip"
    TEMP_DIR="/tmp/edid_teamviewer"
    EDID_PATH="/lib/firmware/edid/1024x768.bin"
    TEAMVIEWER_DEB="teamviewer_amd64.deb"
    TEAMVIEWER_ZIP_URL="https://install.smg.com.tr/AIOSetup/teamviewer_x86.zip"

    # Create temporary directory
    echo "Creating temporary directory for downloads: $TEMP_DIR"
    mkdir -p "$TEMP_DIR"

    # Download EDID ZIP package
    echo "Downloading EDID ZIP package from: $EDID_ZIP_URL"
    wget -O "$TEMP_DIR/edid_1024x768.zip" "$EDID_ZIP_URL"
    if [ $? -ne 0 ]; then
        echo "Failed to download the EDID ZIP package! Please check the URL: $EDID_ZIP_URL"
        exit 1
    fi

    # Extract EDID ZIP package
    echo "Extracting EDID ZIP package..."
    unzip -o "$TEMP_DIR/edid_1024x768.zip" -d "$TEMP_DIR"
    if [ $? -ne 0 ]; then
        echo "Failed to extract the EDID ZIP package!"
        exit 1
    fi

    # Move EDID file to the appropriate location
    echo "Copying EDID file to $EDID_PATH..."
    mkdir -p "$(dirname "$EDID_PATH")"
    cp "$TEMP_DIR/1024x768.bin" "$EDID_PATH"
    if [ $? -ne 0 ]; then
        echo "Failed to copy the EDID file!"
        exit 1
    fi

    # Update GRUB configuration
    echo "Updating GRUB configuration..."
    GRUB_FILE="/etc/default/grub"
    sed -i 's/^GRUB_CMDLINE_LINUX_DEFAULT=".*"/GRUB_CMDLINE_LINUX_DEFAULT="quiet splash drm.edid_firmware=HDMI-A-1:edid\/1024x768.bin video=HDMI-A-1:D"/' "$GRUB_FILE"
    update-grub

    # Verify EDID
    echo "Verifying EDID file..."
    cat "$EDID_PATH" | hexdump -C || { echo "Failed to read EDID file!"; exit 1; }

    # Install required packages for TeamViewer
    echo "Installing required packages..."
    apt-get update -y && apt-get install -y wget

    # Download and install TeamViewer
    echo "Downloading TeamViewer from the primary link..."
    wget -O "$TEMP_DIR/$TEAMVIEWER_DEB" "https://download.teamviewer.com/download/linux/$TEAMVIEWER_DEB"
    if [ $? -ne 0 ]; then
        echo "Primary TeamViewer download failed! Trying alternative ZIP link..."
        wget -O "$TEMP_DIR/teamviewer_x86.zip" "$TEAMVIEWER_ZIP_URL"
        if [ $? -ne 0 ]; then
            echo "Failed to download TeamViewer from both primary and alternative links!"
            exit 1
        fi

        echo "Extracting TeamViewer ZIP package..."
        unzip -o "$TEMP_DIR/teamviewer_x86.zip" -d "$TEMP_DIR"
        if [ $? -ne 0 ]; then
            echo "Failed to extract TeamViewer ZIP package!"
            exit 1
        fi
    fi

    echo "Installing TeamViewer..."
    dpkg -i "$TEMP_DIR/$TEAMVIEWER_DEB"
    if [ $? -ne 0 ]; then
        echo "Failed to install TeamViewer! Attempting to fix missing dependencies..."
        apt-get install -f -y
    fi

    # Set TeamViewer password
    echo "Setting TeamViewer password..."
    teamviewer passwd 1qA2w3eD4R    
    
    # Check HDMI EDID status
    HDMI_STATUS="/sys/class/drm/card0-HDMI-A-1/status"
    if [ -e "$HDMI_STATUS" ]; then
        echo "HDMI status: $(cat "$HDMI_STATUS")"
    else
        echo "HDMI status could not be detected. Please reboot the system."
    fi

    # Start TeamViewer service
    echo "Starting TeamViewer service..."
    
    teamviewer --daemon restart

    sleep 5
    
    systemctl daemon-reload

    sleep 5

    team_info=$(teamviewer info | sed 's/\x1b\[[0-9;]*m//g' | awk '
        BEGIN {
            OFS="\n"
        }
        {
            print $0
        }
    ')

    whiptail --title "Teamviewer Install" --msgbox "$team_info" 20 80

    # Clean up temporary directory
    echo "Cleaning up temporary files..."
    rm -rf "$TEMP_DIR"

    echo "Installation complete! It is recommended to reboot the system."

    sleep 2

    echo "==== system rebooting ..3 ..2 ..1 ==="

    sleep 3 
    
    reboot
}

perform_x86_teamviewer_operation
