lib/update.utils
author Tero Marttila <terom@paivola.fi>
Sun, 22 Dec 2013 15:33:32 +0200
changeset 98 a3734856e0fa
parent 95 a756f317d083
permissions -rw-r--r--
use hosts/dhcp/%** to create dhcp hosts configs
#!/bin/bash
#
# Utility functions

### Command execution
## Execute command, possibly logging its execution.
#
#   cmd     $cmd...
#
# Fails if the command returns an error exit code.
function cmd {
    log_cmd "$@"

    "$@" || die "Failed: $@"
}

## Execute command as a test, logging its execution at log_cmd
#
#   cmd_test $cmd... && ... || ...
#
# Fails if the command returns an error exit code.
function cmd_test {
    log_cmd "$@"

    "$@"
}
## Execute command, prefixing its output on stdout with given indent prefix.
#
#   indent  "    " $cmd...
#
# Output is kept on stdout, exit status is that of the given command.
function indent () {
    local indent="$1"; shift

    "$@" | sed "s/^/$indent/"

    return ${PIPESTATUS[0]}
}


### FS utils
# Create dir if not exists.
function ensure_dir {
    local dir="$1"

    if [ ! -d "$dir" ]; then
        log_warn "Creating output dir: $dir"
        cmd mkdir "$dir"
    fi
}

## Output absolute path
#
#   abspath $path
#
# XXX: improve...?
function abspath () {
    local path="$1"

    echo "$SRV/$path"
}

function _list {
    local glob="$1"
    local test="$2"
    local prefix="$3"

    for file in $glob; do
        [ $test "$file" ] || continue
        [ -n "$prefix" ] && file="${file#$prefix}"

        echo -n "$file "
    done
}

## List names of all files in dir
function list {
    _list "$1/*" '-e' ${2:-$1/}
}

## List names of files in dir:
#
#   list_files $dir
#
function list_files {
    _list "$1/*" '-f' ${2:-$1/}
}

## List names of dirs in dir:
function list_dirs {
    _list "$1/*" '-d' ${2:-$1/}
}

## List names of any files underneath dir or file:
function expand_files {
    _list "$1 $1/**" '-f' ''
}

## Get current unix (utc) timestamp
function unix_time {
    date +'%s'
}