# -*- mode: shell-script; coding: utf-8 -*-
#
# shell-tools
#
# Library of generally useful shell functions.
#
# Copyright (C) 2011 Elmar Hoffmann
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

# Print warning message to standard error
warn ()
{
    local message="$1"

    echo >&2 "$(basename $0): Warning: ${message}"
}

# Print error message to standard error
error ()
{
    local message="$1"

    echo >&2 "$(basename $0): Error: ${message}"
}

# Append trap action to given condition
add_trap ()
{
    local action="$1"
    local condition="$2"

    local traps=$(trap)
    if [ -n "${traps}" ]; then
	local old_action=$(echo "${traps}" \
    | sed --quiet --expression="s/^trap[[:space:]]\+--[[:space:]]\+'\([^']\+\)'[[:space:]]\+${condition}\$/\1/p")
action="${action}; ${old_action}"
    fi
    trap "${action}" "${condition}"
}

_quiet_dd_cleanup ()
{
    local dd_output="$1"

    if [ -f "${dd_output}" ]; then
	sed --expression='/^[0-9]\++[0-9]\+ records \(in\|out\)$/d' "${dd_output}" >&2
	rm -f "${dd_output}"
    fi
}

# Invoke dd(1) filtering out verbose output
quiet_dd ()
{
    local dd_output=$(mktemp -t "$(basename $0)-dd-XXXXXX")
    local saved_traps=$(trap)
    add_trap "_quiet_dd_cleanup \"${dd_output}\"" EXIT
    dd "$@" status=noxfer > "${dd_output}" 2>&1
    _quiet_dd_cleanup "${dd_output}"
    eval "${saved_traps}"
}

# Terminate with an error message if not running with root privileges
require_root ()
{
    if [ $(id -u) -ne 0 ]; then
	error "This program needs to be run with root privileges."
	exit 1
    fi
}
