#!/bin/bash
# common functionalities among velvet tools

# makes sure we are running as root
need_root() {
    if [ "$(whoami)" != "root" ]; then
        echo "This script must be run as root user."
        exit
    fi
}

get_kver() {
    if [ "$1" == "" ]; then
        echo "Note. no kernel was specified, using current kernel."
        kver=$(uname -r)
    else
        #kernel presence check would be nice :3
        kver=${1}
    fi

    # it's not like we can stupid proof every file
    if [ ! -e "/boot/Image-${kver}" ]; then
        echo "Image-${kver} seems to be missing."
        echo "ple ple ple, your kernel version is likely wrong !"
        exit 1
    fi

    echo "The chosen kernel is ${kver}"
}

need_confirmation(){
    echo "[y/N]"
    read confirmation
    if [ "$confirmation" != "y" ]; then
        echo "canceled."
        exit
    fi
}

out_of_memory(){
    echo "Your /boot partition is out of memory."
    exit
}

get_y_or_n_answer(){
    echo "[y/N]"
    read answer
    # add fix for capital letters and different languages?
}

save_pwd(){
    oldpwd=$(pwd)
}

restore_pwd(){
    if [ "$oldpwd" != "" ]; then
        cd "$oldpwd"
    fi
}

default_config(){
    flash=auto
    main_part=auto
    test_part=auto
    init_gen_hook=y
}

load_config(){
    if [ ! -f /etc/velvettools/config ]; then
        default_config
        return
    fi

    source /etc/velvettools/config

    if [ "$flash" == "" ]; then
        flash=manual
    fi

    if [ "$main_part" == "" ]; then
        main_part=auto
    fi

    if [ "$test_part" == "" ]; then
        test_part=auto
    fi

    if [ "$init_gen_hook" == "" ]; then
        init_gen_hook=y
    fi
}

get_kparam(){
    PARAM=$1
    cat /proc/cmdline | tr ' ' '\n' | grep "$PARAM" | sed "s/${PARAM}=//"
}

hash_file(){
    FILE=$1
    md5sum $FILE | cut -c -32 -n
}
