# vim: filetype=sh

# basic routines
# --------------
missing_or_empty()
{
    f="$1"
    if [ ! -e "$f" ]
    then
        echo 1
        return
    else
        if [ "$(cat "$f" | wc -l)" -eq 0 ]
        then
            echo 1
            return
        fi
    fi
    echo 0
}

num_dir_entries() {
    d="$1"
    if [ ! -d "$d" ]
    then
        echo 0
    else
        ls -1 "$d" | wc -l
    fi
}

abspath()
{
    echo "$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
}

print_last_word()
{
    awk '{print $NF}'
}

# divide %1/%2 rounding up
ceil()
{
    divide=$1
    by=$2
    echo $(((divide+by-1)/by))
}

estimated_size_mb()
{
    du -sm "$1" | awk '{print $1}'
}

real_size_human_readable()
{
    du -sh --apparent-size "$1" | awk '{print $1}'
}

device_size_mb()
{
    size_b=$(blockdev --getsize64 $1)
    echo $((size_b/1024/1024))
}

size_as_mb()
{
    echo $(($(echo $1 | sed -e "s/M//" -e "s/G/*1024/")))
}

check_integer() {
    case "$1" in
        ''|*[!0-9]*)
            return 1 ;;   # not a number
        *)
            return 0 ;;   # number
    esac
}

sum_lines() {
    exp="$(paste -sd+ -)"
    [ "$exp" = "" ] && echo 0 || echo "$(($exp))"
}

# grep returns non-zero if no line is found.
# in some cases, having no line is expected
# (e.g. in the case of error lines)
# thus the or-true construct.
happy_grep()
{
    grep "$@" || true
}

# get total size needed taking into account
# an overhead.
# $1: the initial size (not taking the overhead into account)
# $2: percent of overhead
# return value: the size needed (such that applying the
#               overhead would get $1 again)
apply_overhead_percent()
{
    echo $((($1)*100/(100-($2))))
}

quiet()
{
    $* >/dev/null
}

wait_for_device()
{
	while [ ! -e "$1" ]
	do
		sleep 0.1
	done
}

get_vg_name()
{
    case "$1" in
        "draft")
            echo "DRAFT_$2"
            ;;
        "final")
            echo "DBSTCK_$2"
            ;;
    esac
}

get_rootfs_uuid()
{
    image_name="$1"     # final or draft
    cat $DBSTCK_TMPDIR/$image_name/rootfs_vol/uuid
}
