#!/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="serial1"
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() {
	MODEL=`cat /tmp/sysinfo/model`
	if [ "$MODEL" == "G414" ]; then
		ps | egrep -i "serial /dev/ttyS1" | grep -v grep | awk '{print $1}' | xargs kill -9 2>/dev/null
	else
		ps | egrep -i "serial /dev/ttyS6" | grep -v grep | awk '{print $1}' | xargs kill -9 2>/dev/null
	fi
}

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

stop_getty() {
    if [[ -e /tmp/gettyconsole2.pid ]]; then
        getty_fn_pid=`cat /tmp/gettyconsole2.pid 2>/dev/null || echo 0`
        if [[ $getty_fn_pid -ne 0 ]]; then
            logger -t serial -p info "stop console2 $getty_fn_pid"
            kill -KILL $getty_fn_pid
            sleep 1
            GETTY_PID=`cat /tmp/getty2.pid 2>/dev/null || echo 0`
            if [[ $GETTY_PID != 0 ]]; then
                kill -KILL $GETTY_PID
                rm -f /tmp/getty2.pid
            fi
            rm -f /tmp/gettyconsole2.pid
        fi
    fi
}
boot() {
    lock
    mode="`uci get serial1.@configuration[0].mode`"
    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
    sku=`cat /proc/device-tree/lantronix/hwcfg 2>/dev/null | tr -d '\n' | grep -eG526GP1AS1 -eG526GP12S1 -eG526GP17S1 -eG526GP1CS1`
    if [[ "$sku" != "" ]]; then
        return 0
    fi
	/usr/sbin/serial2.sh 2>/dev/null
    mode="`uci get serial1.@configuration[0].mode`"
    if [[ "$mode" == "console" && ! -e /tmp/gettyconsole2.pid ]]; then
        #stop getty
        stop_getty
        #run getty
        run_getty &
        sleep 5
        getty_fn_pid=$!
        echo $getty_fn_pid > /tmp/gettyconsole2.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
}

