#!/bin/bash
#
# update console postinstall hook
#

set -e

: ${vyatta_prefix:=/opt/vyatta}
: ${vyatta_exec_prefix:=$vyatta_prefix}
: ${vyatta_sbindir:=${vyatta_exec_prefix}/sbin}

source ${vyatta_sbindir}/vyatta-install-image.functions

function update_console_console ()
{
    # nothing to configure and run by default
    echo "VII_POSTINSTALL_VYATTA_MISC=${VII_POSTINSTALL_VYATTA_MISC:-true}"
}

function update_console_run ()
{
    local root_dir=${1?Missing argument}
    local image_name=${2?Missing argument}

    local grub_cfg="${root_dir}/boot/grub/grub.cfg"

    local speed=$(cli-shell-api returnValue /system/console/device/ttyS0/speed)
    local old_speed=$(sed -n 's/^serial.*--speed=\([0-9][0-9]*\)/\1/p' $grub_cfg)

    if [ -n "$old_speed" -a -n "$speed" -a \( "$old_speed" != "$speed" \) ]; then
        sed -i -e "s/^serial .*$/serial --unit=0 --speed=$speed/" \
               -e "s/^\(.*\)console=ttyS0,[0-9][0-9]*\(.*\)$/\1console=ttyS0,$speed\2/" $grub_cfg
    fi
}

case "$1" in
    configure)
        update_console_console
        ;;
    run)
        [ "${VII_POSTINSTALL_VYATTA_MISC}" = 'true' ] && update_console_run $2 $3
        ;;
    *)
        fail_exit "$0: unknown command: \"$1\""
        ;;
esac

exit 0
