#!/bin/sh /etc/rc.common
START=99

APP="terminal"
NAME=terminald
PIDFILE="/var/run/$NAME.pid"
DAEMON="/bin/terminald"

boot() {
    start
    return 0
}

lock() {
    until [[ -f /tmp/system.initialized && -f /tmp/system.evo.initialized ]]
    do
        sleep 5
    done
    while true; do
        if mkdir /var/lock/$APP; then
            break
        else
            usleep 500000
        fi
    done
}

unlock() {
    rm -rf /var/lock/$APP
}

genarate_menu() {
     # Define the output file
    output_file="/tmp/terminalDisplay.txt"

    # Get total number of ports
    total_ports=$(cat /proc/device-tree/lantronix/hwcfg | tr -d -c 0-9 | cut -c 3-)

    # Start capturing output
    #{
        #echo "Total Ports: $total_ports"
        #echo "Listing Serial Port Names:"

        # Get all serial-related UCI sections
        uci_sections=$(uci show | grep -o "^serial[0-9]*" | sort -u)
        [ -f $output_file ] && rm "$output_file"
        # Check if any serial sections exist
        if [ -z "$uci_sections" ]; then
            echo "No serial ports found in UCI."
            exit 1
        fi

        # Counter for printing port numbers
        count=1

        # Loop through all serial sections
        for section in $uci_sections; do
            serial_name=$(uci get ${section}.Line.Name 2>/dev/null)

            # Check if a name exists for this section
            if [ -n "$serial_name" ]; then
                echo "$count: $serial_name" >> "$output_file"
                count=$((count + 1))
            fi
        done
   # } | tee "$output_file"
}

start() {
    [ -f /proc/device-tree/lantronix/ftm_mode ] && {
        ftm_mode=$(cat /proc/device-tree/lantronix/ftm_mode)
        [ "$ftm_mode" != "0" ] && return
    }

    #enable=$(uci get terminal.config.enable 2>/dev/null)
    terminal_type=$(uci get terminal.config.Terminal_Type 2>/dev/null)
    login_menu=$(uci get terminal.config.Login_Connect_Menu 2>/dev/null)

    logger "Terminal: Starting with type=$terminal_type, login_menu=$login_menu"

    #if [[ "$login_menu" == "1" ]]; then
     #   start-stop-daemon -S -m -p "$PIDFILE" -x "$DAEMON" &
    #fi

    lock
    ltrx_mhcfgupdate terminal
    unlock
    /usr/sbin/update_passwd_file.sh
    genarate_menu

}


stop() {
    logger "Terminal: Stopping"
    /usr/sbin/update_passwd_file.sh
    pidof terminald | xargs kill -9 2>/dev/null
    rm -f "$PIDFILE"
}

reload() {
    logger "Terminal: Reloading"
    stop
    start
}
