#!/bin/bash

function smgaio () {

    #download smgaio
    wget https://install.smg.com.tr/smgaio.sh

    #give permission & run
    #sudo su
    sudo chmod +x smgaio.sh
    ./smgaio.sh
}

function change_cpu_frequency() {

    BACKTITLE="CPU Configuration"
    SUDO_USER=$(whoami)
    SUDO="sudo -u $SUDO_USER"

    POLICY="policy0"
    [[ $(grep -c '^processor' /proc/cpuinfo) -gt 4 ]] && POLICY="policy4"
    [[ ! -d /sys/devices/system/cpu/cpufreq/policy4 ]] && POLICY="policy0"
    [[ -d /sys/devices/system/cpu/cpufreq/policy0 && -d /sys/devices/system/cpu/cpufreq/policy2 ]] && POLICY="policy2"

    # Select minimum CPU speed
    MIN_SPEED=$(dialog --backtitle "$BACKTITLE" --title "Select minimum CPU speed" \
        --menu "Choose minimum CPU speed:" 15 50 4 \
        $(cat /sys/devices/system/cpu/cpufreq/$POLICY/scaling_available_frequencies | tr ' ' '\n' | awk '{print $1 " " $1}') 3>&1 1>&2 2>&3 3>&-)
    
    # Select maximum CPU speed
    MAX_SPEED=$(dialog --backtitle "$BACKTITLE" --title "Select maximum CPU speed" \
        --menu "Choose maximum CPU speed:" 15 50 4 \
        $(cat /sys/devices/system/cpu/cpufreq/$POLICY/scaling_available_frequencies | tr ' ' '\n' | awk '{print $1 " " $1}') 3>&1 1>&2 2>&3 3>&-)
    
    # Select CPU governor
    GOVERNOR=$(dialog --backtitle "$BACKTITLE" --title "Select CPU governor" \
        --menu "Choose CPU governor:" 15 50 4 \
        $(cat /sys/devices/system/cpu/cpufreq/$POLICY/scaling_available_governors | tr ' ' '\n' | awk '{print $1 " " $1}') 3>&1 1>&2 2>&3 3>&-)
    
    # Confirm and apply changes
    if dialog --colors --title " Apply and save changes " --backtitle "$BACKTITLE" --yes-label "OK" --no-label "Cancel" --yesno \
        "\nCPU frequency will be within \Z1$(($MIN_SPEED / 1000))\Z0 and \Z1$(($MAX_SPEED / 1000)) MHz\Z0. The governor \Z1$GOVERNOR\Z0 will decide which speed to use within this range." 9 58; then
        sudo sed -i "s/MIN_SPEED=.*/MIN_SPEED=$MIN_SPEED/" /etc/default/cpufrequtils
        sudo sed -i "s/MAX_SPEED=.*/MAX_SPEED=$MAX_SPEED/" /etc/default/cpufrequtils
        sudo sed -i "s/GOVERNOR=.*/GOVERNOR=$GOVERNOR/" /etc/default/cpufrequtils
        sudo systemctl restart cpufrequtils
        sync
    fi

}

function monitor_cpu_frequency() {
    CPUMHZFILE="/tmp/cpuwatch.txt"
    
    # Clear the file at the start
    > $CPUMHZFILE
    
    # Run the cpufreq-info command periodically and append the output to the file
    (while true; do 
        echo "$(date '+%Y-%m-%d %H:%M:%S')" >> $CPUMHZFILE
        cpufreq-info -fm >> $CPUMHZFILE
        echo "" >> $CPUMHZFILE
        sleep 2
    done) &
    WATCH_PID=$!

    # Use dialog command to display the file content
    dialog --title "CPU MHz Monitor" --tailbox $CPUMHZFILE 20 70

    # Stop the background loop
    kill $WATCH_PID

    # Remove the temporary file
    rm -f $CPUMHZFILE
}

function monitor_cpu_temperature() {
    TEMPFILE="/tmp/tempcpu.txt"

    # Run armbianmonitor -m in the background, redirecting its output to a temporary file
    sudo armbianmonitor -m > $TEMPFILE &
    
    # Wait a short time to ensure the process starts
    sleep 1
    
    # Find the correct PID of the armbianmonitor -m process
    PID=$(ps aux | grep 'armbianmonitor -m' | grep -v grep | awk '{print $2}')

    # Use dialog to display the content of the temporary file in a tailbox
    dialog --title "CPU Temperature Monitor" --tailbox $TEMPFILE 20 70

    # When the dialog window is closed, terminate the background process
    sudo kill -9 $PID

    # Remove the temporary file
    rm -f $TEMPFILE
}

function track_cpu_processes() {
    htop
}

function resolv_conf() {
    # Use dialog to prompt the user for a choice
    dialog --backtitle "resolv.conf Lock/Unlock" --title "Make a Choice" \
    --menu "Select an option to lock or unlock the resolv.conf file:" 15 50 2 \
    1 "Lock" \
    2 "Unlock" 2> /tmp/resolv_conf_choice

    # Read the user's choice
    choice=$(cat /tmp/resolv_conf_choice)

    # Perform the action based on the choice
    case $choice in
        1)
            # Lock the file
            sudo chattr +i /etc/resolv.conf
            dialog --msgbox "The resolv.conf file has been locked." 6 40
            ;;
        2)
            # Unlock the file
            sudo chattr -i /etc/resolv.conf
            dialog --msgbox "The lock on the resolv.conf file has been removed." 6 40
            ;;
        *)
            dialog --msgbox "Invalid choice." 6 40
            ;;
    esac

    # Clean up the temporary file
    rm -f /tmp/resolv_conf_choice
}

function network_interfaces() {
    # Use dialog to prompt the user for a choice
    dialog --backtitle "Etc/network/interfaces Lock/Unlock" --title "Make a Choice" \
    --menu "Select an option to lock or unlock the Etc/network/interfaces file:" 15 50 2 \
    1 "Lock" \
    2 "Unlock" 2> /tmp/etc_conf_choice

    # Read the user's choice
    choice=$(cat /tmp/etc_conf_choice)

    # Perform the action based on the choice
    case $choice in
        1)
            # Lock the file
            sudo chattr +i /etc/network/interfaces
            dialog --msgbox "The Etc/network/interfaces file has been locked." 6 40
            ;;
        2)
            # Unlock the file
            sudo chattr -i /etc/network/interfaces
            dialog --msgbox "The lock on the Etc/network/interfaces file has been removed." 6 40
            ;;
        *)
            dialog --msgbox "Invalid choice." 6 40
            ;;
    esac

    # Clean up the temporary file
    rm -f /tmp/etc_conf_choice
}

function monitor_internet_traffic() {
    (
    # Step 1: Checking if iftop is installed
    echo "10"; echo "Checking if iftop is installed"; sleep 1

    if dpkg -l | grep iftop >/dev/null 2>&1; then
        echo "30"; echo "iftop is already installed."; sleep 1
    else
        echo "20"; echo "iftop is not installed. Installing..."; sleep 1
        sudo apt update >/dev/null 2>&1
        sudo apt install iftop -y >/dev/null 2>&1
        if dpkg -l | grep iftop >/dev/null 2>&1; then
            echo "50"; echo "iftop installation successful."; sleep 1
        else
            echo "100"; echo "iftop installation failed."; sleep 1
            return 1
        fi
    fi

    echo "100"; echo "Process completed."; sleep 1
    ) | dialog --title "Internet Traffic Monitoring" --gauge "Please wait..." 10 70 0

    # Network interface selection menu
    choice=$(dialog --menu "Please select the network interface to monitor:" 15 50 2 \
        1 "eth0" \
        2 "wlan0" \
        3>&1 1>&2 2>&3)

    case $choice in
        1)
            sudo iftop -i eth0 -n -P
            ;;
        2)
            sudo iftop -i wlan0 -n -P
            ;;
        *)
            dialog --msgbox "Invalid choice. Exiting." 5 40
            return 1
            ;;
    esac
}

#function test_internet_speed() {}

#function test_cdn_connection() {}

function SMGBox() {
    while true; do
        # Read current CPU info
        MIN_FREQ=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq)
        MAX_FREQ=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq)
        GOVERNOR=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)

        # Convert values to MHz
        MIN_FREQ_MHZ=$(($MIN_FREQ / 1000))
        MAX_FREQ_MHZ=$(($MAX_FREQ / 1000))

        CHOICE=$(dialog --backtitle "SMGBox/Raspberry/TinkerboardR2.0 Tweaker & Monitor V.1.0.0" --title "Configure based ARM & ARM64 devices" \
            --menu "SoC runs between $MIN_FREQ_MHZ and $MAX_FREQ_MHZ MHz using $GOVERNOR governor.\n\nSupport: teknik@smg.com.tr\n\nSelect an option:" 20 70 10 \
            "SMGAIO" "Download & Run" \
            "CPU Freq" "Change CPU freq" \
            "CPU Monitoring" "MHz" \
            "CPU Temperature" "Monitoring" \
            "Resolv.conf" "Lock & Unlock" \
            "Etc/network/interfaces" "Lock & Unlock" \
            "Htop" "Task Monitoring" \
            "Internet Traffic" "Monitoring" \
            "Speed Test" "For internet connection" \
            "CDN Connection Test" "" 3>&1 1>&2 2>&3)

        case $CHOICE in
            "SMGAIO")
                smgaio
                ;;
            "CPU Freq")
                change_cpu_frequency
                ;;
            "CPU Monitoring")
                monitor_cpu_frequency
                ;;
            "CPU Temperature")
                monitor_cpu_temperature
                ;;
            "Resolv.conf")
                resolv_conf
                ;;
            "Etc/network/interfaces")
                network_interfaces
                ;;
            "Internet Traffic")
                monitor_internet_traffic
                ;;
            "Speed Test")
                test_internet_speed
                ;;
            "CDN Connection Test")
                test_cdn_connection
                ;;
            "Htop")
                track_cpu_processes
                ;;
            *)
                break
                ;;
        esac
    done
}

SMGBox
