#!/bin/sh /etc/rc.common
#
# Copyright (C) 2014-2020, Lantronix, Inc. All Rights Reserved.
#           7535 Irvine Center Drive, Suite 100
#           Irvine, CA 92618 USA

# Permission to use, copy, modify this software for any
# purpose is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.

# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#


START=99

APP="serial"
lock() {
    while true; do
        if mkdir /var/lock/$APP; then
            logger -p "user.debug" "$APP$1 $$ : lock"
            break
        else
            logger -p "user.debug" "$APP$1 $$ : wait"
            usleep 500000
        fi
    done
}

unlock() {
    logger -p "user.debug" "$APP$1 $$ : unlock"
    rm -rf  /var/lock/$APP
}

kill_serial() {
	ps | egrep -i "serial /dev/ttyS3" | grep -v grep | awk '{print $1}' | xargs kill -9 2>/dev/null
}

run_getty() {
    # Start getty on tty3
    logger -t serial -p info "start console"
    while true; do
        baud=`uci -q get serial.Line.Baud_Rate || echo 0`
        if [[ $baud != 0 && -e /dev/ttyS3 ]]; then
                logger -t serial -p info "rungetty $baud ttyS3"
                GETTY_PID=`cat /tmp/getty.pid 2>/dev/null || echo 0`
                if [[ $GETTY_PID != 0 ]]; then
                    kill -KILL $GETTY_PID
                    rm -f /tmp/getty.pid
                fi
                setsid /sbin/getty -L ttyS3 $baud vt100 &
                GETTY_PID=$!
                echo $GETTY_PID > /tmp/getty.pid
                wait $GETTY_PID
                sleep 1  # Optional delay before respawning
                logger -t serial -p info "respawing console"
        else
                logger -t serial -p info "unable to rungetty baud:0, ttyS3"
                sleep 5
        fi
    done
}

stop_getty() {
    if [[ -e /tmp/gettyconsole.pid ]]; then
        getty_fn_pid=`cat /tmp/gettyconsole.pid 2>/dev/null || echo 0`
        if [[ $getty_fn_pid -ne 0 ]]; then
            logger -t serial -p info "stop console $getty_fn_pid"
            kill -KILL $getty_fn_pid
            sleep 1
            GETTY_PID=`cat /tmp/getty.pid 2>/dev/null || echo 0`
            if [[ $GETTY_PID != 0 ]]; then
                kill -KILL $GETTY_PID
                rm -f /tmp/getty.pid
            fi
            rm -f /tmp/gettyconsole.pid
        fi
    fi
}

boot() {
    mode="`uci get serial.@configuration[0].mode`"
    lock
    if [[ "$mode" == "transparent" ]] || [[ "$mode" == "manageddevice" ]] || [[ "$mode" == "console" ]] || [[ "$mode" == "none" ]] || [[ "$mode" == "modbus" ]]
    then
        start
        rm -f /tmp/luci_message_tunnel*
        rm -f /tmp/luci_message_serial*
	fi
    unlock
	return 0
}

start() {
    logger -t serial -p debug "start"
    kill_serial
	/usr/sbin/serial.sh 2>/dev/null
    mode="`uci get serial.@configuration[0].mode`"
    if [[ "$mode" == "console" && ! -e /tmp/gettyconsole.pid ]]; then
        #stop getty
        stop_getty
        #run getty
        run_getty &
        sleep 5
        getty_fn_pid=$!
        echo $getty_fn_pid > /tmp/gettyconsole.pid
    fi
}

stop() {
    logger -t serial -p debug "stop"
    kill_serial
    if [[ ! -n "$REASON" || "$REASON" != "hotplug" ]]; then
	    stop_getty
    fi
	return 0
}
reload() {
    lock
    logger -t serial -p debug "reload"
    stop
    start
    unlock
}

