#!/bin/sh

INITTAB="/etc/inittab"

system_console=`cat /sys/class/tty/console/active`

if [ -f "$INITTAB" ]
then
    ttc=`grep askfirst $INITTAB | awk -F ':' '{ print $1 }' | sed 's,#,,g' | head -1` 
    if [ -z "$ttc" ]; then
       ttc=`grep respawn $INITTAB | awk -F ':' '{ print $1 }' | sed 's,#,,g' | head -1` 
    fi
fi

if [ -z "$ttc" ]
then
     echo "error"
     exit 255
fi

if [ "$1" = "start" ]
then
    if [ -n "`grep "#$ttc" $INITTAB`" ]
    then
        chmod 666 /dev/$ttc
    else
        chmod 600 /dev/$ttc
    fi
fi

if [ "$1" = "stop" ]
then
    true
fi

if [ "$1" = "disable" ]
then
    echo "Stop console $ttc"
    if [ -z "`grep "#$ttc" $INITTAB`" ]
    then
        sed -i -e "s/\(^.*$ttc.*$\)/#\1/" $INITTAB
        init -q
        sync
        if [ "$system_console" == "$ttc" ]
        then  
            if [ -f /sys/class/tty/$ttc/console_status ]  
            then
                echo 0 > /sys/class/tty/$ttc/console_status
            else 
                dmesg -n 1
            fi
        fi    
        ln -sf /dev/null /dev/console
        chmod 666 /dev/$ttc
    fi
fi


if [ "$1" = "enable" ]
then
    echo "Start console $ttc"
    if [ -n "`grep "#$ttc" $INITTAB`" ]
    then
        sed -i -e "s,#$ttc,$ttc,g" $INITTAB
        init -q
        sync
        if [ -z $system_console ]
        then 
            if [ -f /sys/class/tty/$ttc/console_status ]
            then
                echo 1 > /sys/class/tty/$ttc/console_status
            fi
        fi    
        rm -rf /dev/console
        mknod -m 622 /dev/console c 5 1
        chmod 600 /dev/$ttc
    fi
fi

if [ "$1" = "status" ]
then
    if [ -n "`grep "#$ttc" $INITTAB`" ]
    then
        echo "no"
    else
        echo "yes"
    fi
fi
