#!/bin/sh

# author : Nicolas Chipaux <aegiap@gandi.net> for GANDI
# all rights reserved.

umask 022

[ -f /etc/gandi/plugins-lib ] && . /etc/gandi/plugins-lib || exit 1
load_config

if [ $CONFIG_CONSOLE -eq 0 ]; then
    exit 0
fi

# Common creation
[ -e /dev/console ] || mknod /dev/console c 5 1
[ -e /dev/null ] || mknod /dev/null c 1 3
[ -e /dev/ptmx ] || mknod /dev/ptmx c 5 2
[ -e /dev/zero ] || mknod /dev/zero c 1 5

# Detect all tty devices on the system. We force 'console' as it should work in
# all linux system.
ttydevlist=''
list_ttydev() {
    ttydev1=$(dmesg | grep -o 'console \[.*\] enabled' | sed -e 's/console \[//' -e 's/\] enabled//')
    ttydev2=$(dmesg | awk '/Xen virtual console successfully installed as / { print $NF }')
    ttydevlist=$(echo $ttydev1 $ttydev2 | sed -e 's/ /\n/g' | sort -u | xargs)

    # if no tty is detected, we fallback to /dev/console
    if [ "o$ttydevlist" = "o" ]; then
        ttydevlist="console"
    fi

    unset ttydev1 ttydev2
}

# Detect the type of getty used in inittab file
detect_getty() {
    mingettybin=$(which mingetty 2> /dev/null)
    agettybin=$(which agetty 2> /dev/null)
    gettybin=$(which getty 2> /dev/null)

    if [ ! "0$gettybin" = "0" ]; then
            grep -q "$gettybin" /etc/inittab && \
		ttyptrn="/sbin/getty [0-9][0-9]*"
    fi
    if [ ! "0$mingettybin" = "0" ]; then
            grep -q "$mingettybin" /etc/inittab && \
		ttyptrn="/sbin/mingetty"
    fi
    if [ ! "0$agettybin" = "0" ]; then
            grep -q "$agettybin" /etc/inittab && \
		ttyptrn="/bin/agetty"
    fi
}

if [ ! -d /proc/xen -a -e /sys/bus/virtio/drivers/virtio_console ]; then
    [ -e /dev/ttyS0 ] || mknod /dev/ttyS0 c 4 64
    ttydevlist='ttyS0'
else
    # Get the list of all console and tty available device on the vm
    # the list is available in $ttydevlist
    list_ttydev
fi

# initab is the traditionnal method to config boot process.
# especially which console to start. One new method is to use
# event.d directory with many files config.
# In some distribution, both method are used : a simple inittab
# and everything in /etc/event.d/
config_file=/etc/inittab
if [ -e $config_file ]; then
    ttyptrn=''
    detect_getty

    if [ "p$ttyptrn" = 'p' ]; then
        echo "No getty found in /etc/inittab. "
    else 

        ttydevlistsize=0
        for tty in $ttydevlist; do
            ttydevlistsize=$(( $ttydevlistsize + 1))
        done

        ttyparam=$(grep -o -e "$ttyptrn" /etc/inittab | uniq  | tail -1)
        if [ "o$ttyparam" = "o" ]; then
            echo "Error when getting *getty param from file. Exiting."
            exit 1
        fi

        quote="console configuration by gandi-config"
        if ( ! grep -q "^# $quote" /etc/inittab); then
            tempfile_=$(mktemp)
            cp /etc/inittab "${tempfile_}"

            echo "" >> "${tempfile_}"
            echo "# $quote" >> "${tempfile_}"

            # We disable all getty in the inittab file
            LC_ALL=C LANG=C perl -pi \
                -e "s,(^[1-6]:.*:respawn:/sbin/.*getty.*),#\$1,g" \
                "${tempfile_}"

            # For all detected tty device, we enable them in the copy of inittab
            idx_=$ttydevlistsize
            for tty in $ttydevlist; do
                if ( ! grep -q -e "^[0-9]:.*respawn:.*$tty" "${tempfile_}" ); then
                    echo "${idx_}:2345:respawn:$ttyparam $tty" >> "${tempfile_}"
                    idx_=$(( $idx_ - 1 ))
                fi
            done

            cp /etc/inittab /etc/inittab.orig
            mv -f "${tempfile_}" /etc/inittab

            # as we change the /etc/inittab file, we restart init
            init q
        fi
    fi
fi
# end config for /etc/inittab


# Ubuntu is using upstart now. All config are in /etc/init.
eventdir=/etc/init
if [ -d "$eventdir" ]; then

    if [ -e "$eventdir"/tty1.conf ]; then
        [ -f /sbin/initctl ] && initctl --quiet stop tty1
	for tty in $ttydevlist; do
            if [ "$tty" != 'tty1' ]; then
                sed -e "s/tty1/$tty/g" \
                    -e 's/^#\(start\|stop\|respawn\|exec\)/\1/g' \
                    "$eventdir"/tty1.conf > "$eventdir"/"$tty.conf.gandi"
                mv -f "$eventdir"/"$tty.conf.gandi" "$eventdir"/"$tty.conf"
            fi
            # do not need the error output
            [ -f /sbin/initctl ] && initctl --quiet start $tty 2> /dev/null
	done
    fi
fi


# Some older distribution are using an alternate boot process.
# All config are in /etc/event(s).d
if [ -d /etc/events.d -o -d /etc/event.d ]; then
    
    eventdir=/etc/event.d
    [ -d /etc/events.d ] && eventdir=/etc/events.d

    if [ ! -e "$eventdir/tty1" ]; then
	for tty in $ttydevlist; do
            if [ "$tty" != 'tty1' ]; then
                sed -e "s/tty1/$tty/g" \
                    -e 's/^#\(start\|stop\|respawn\|exec\)/\1/g' \
                    $eventdir/tty1 > "$eventdir/$tty.gandi"
                mv -f "$eventdir/$tty.gandi" "$eventdir/$tty"
            fi
	done
    fi
fi
# end config for /etc/event.d or /etc/events.d/


config_file=/etc/default/console-setup
if [ -e "/$config_file" ]; then
    LC_ALL=C LANG=C perl -pi \
       -e "s/^ACTIVE_CONSOLES=.*/ACTIVE_CONSOLES=\"\/dev\/console\"/" \
       "$config_file"
fi

config_file=/etc/securetty
if [ -e "$config_file" ]; then
    grep -q console "$config_file" > /dev/null || \
	echo console >> $config_file
    grep -q "$ttydev" "$config_file" > /dev/null || \
	echo "$ttydev" >> $config_file
fi


exit 0
