#!/bin/bash
# Led Control Script Aria_keratone
INTERVAL=20
LEDLOW=0 # LED mati
LEDHI=1 # LED hidup
CPU_SHUTDOWN=54000 # Suhu CPU threshold
cur_led=0
new_led="$LEDHI" # Mulai dengan LED hidup

# Fungsi untuk mengatur LED
led_set() {
    cur_led=$1
    echo "Mengatur LED ke ${cur_led}."

    # Pastikan GPIO telah diekspor
    if [ ! -d /sys/class/gpio/gpio507 ]; then
        echo 507 > /sys/class/gpio/export
    fi

    # Set direction GPIO
    echo "out" > /sys/class/gpio/gpio507/direction

    # Kirim nilai ke GPIO
    if [ "$1" -eq "$LEDLOW" ]; then
        echo "0" | sudo tee /sys/class/gpio/gpio507/value  # Mengatur LED mati
        echo "LED dimatikan."
    else
        echo "1" | sudo tee /sys/class/gpio/gpio507/value  # Mengatur LED hidup
        echo "LED dihidupkan."
    fi
}

trap 'led_set $LEDLOW; exit' SIGINT SIGTERM # Mematikan LED saat menerima sinyal interupsi

# Mengontrol LED
while :; do
    # Ambil nilai suhu CPU
    cpu=$(cat /sys/class/hwmon/hwmon0/temp1_input)

    # Cek jika CPU memiliki nilai
    if [ -z "$cpu" ]; then
        echo "Gagal mendapatkan suhu CPU!"
        sleep $INTERVAL
        continue
    fi

    echo "Suhu CPU saat ini: $cpu"

    # Logika untuk menetapkan LED 
    if [ "$cpu" -gt "$CPU_SHUTDOWN" ]; then   # Jika suhu CPU > 54000
        new_led="$LEDHI"  # LED hidup
    else   # Jika suhu CPU <= 54000
        new_led="$LEDLOW"  # LED mati
    fi

    echo "LED baru: $new_led"

    # Set LED only if new_led has changed
    if [ "$new_led" -ne "$cur_led" ]; then
        led_set "$new_led"
        cur_led="$new_led" # Update current LED status
    fi

    sleep $INTERVAL
done