#!/bin/bash
#
# Configure kdump
# Source functions library
. /etc/init.d/functions
. /usr/libexec/ovirt-functions

trap '__st=$?; stop_log; exit $__st' 0
trap 'exit $?' 1 2 13 15

warn() { printf '%s\n' "$*" >&2; }

check() {
if ! is_local_storage_configured; then
    warn "Configure local storage before configuring kdump."
    exit 99
fi
if ! network_up; then
    warn "Configure network before configuring kdump."
    exit 99
fi
}

function write_kdump_config {
    cat > /etc/kdump.conf <<EOF
default reboot
net $1
EOF
    ovirt_store_config /etc/kdump.conf
    return 0
}

function kdump_confirm {

    local server=$1
    local server_type=$2

    printf "\nkdump $server_type Configuration\n"
    printf "\n$server_type: $server \n\n"
        if ask_yes_or_no "Confirm these values ([Y]es/[N]o)?"; then
            write_kdump_config $server
            if [ $server_type = "SSH" ]; then
                # /dev/console is occupied by firstboot, need to make /dev/tty available
                rm -rf /dev/tty
                ln -s /dev/console /dev/tty
                service kdump propagate
            fi
            service kdump restart
        fi

}

function nfs_config {
    nfs_server=""
    printf "\n"
    read -p "Enter nfs server path (example.redhat.com:/var/crash): " -er
    test -z "$REPLY" && return 1
    nfs_server="$REPLY"
    kdump_confirm $nfs_server NFS
}


function ssh_config {
    ssh_login=""
    printf "\n"
    read -p "Enter ssh user/hostname (root@example.redhat.com): " -er
    test -z "$REPLY" && return 1
    ssh_login="$REPLY"
    kdump_confirm $ssh_login SSH
}

function restore_config {
    cat > /etc/kdump.conf <<\EOF
default reboot
ext4 /dev/HostVG/Data
path /core
EOF
    ovirt_store_config /etc/kdump.conf
    service kdump restart
}

NFS="Setup NFS Configuration"
SSH="Setup SSH Configuration"
RESTORE="Restore Default Configuration"
QUIT="Return to the Hypervisor Configuration Menu"

if [ "$1" = "AUTO" ]; then
    if [ -n "$OVIRT_KDUMP_NFS" ]; then
        write_kdump_config $OVIRT_KDUMP_NFS
    fi
else
    check
    printf "\n\n kdump Configuration\n\n"
    while true; do
        PS3="Choose an option: "
        select option in "$NFS" "$SSH" "$RESTORE" "$QUIT"
          do

          case $option in
              $NFS) nfs_config; break;;
              $SSH) ssh_config; break;;
              $RESTORE) restore_config; break;;
              $QUIT) exit;;
          esac
        done

        printf "\n"
    done
fi
