###
# LOGGING

# XXX what if the message starts with a minus??
debug()
{
    if test "$debug"
    then
        echo "$*" 1>&2
        if test "$logfile"
        then
            echo "$*" >> "$logfile"
        fi
    fi
    if test "$syslog"
    then
        logger -t $(get_script_name) -p user.debug "$*"
    fi
}

# XXX what if the message starts with a minus??
error()
{
    echo "$*" 1>&2
    if test "$logfile"
    then
        echo "$*" >> "$logfile"
    fi
    if test "$syslog"
    then
        logger -t $(get_script_name) -p user.err "$*"
    fi
    if test "$sms"
    then
        echo "$*" | sendsms ${phone}
    fi
}

# XXX what if the message starts with a minus??
info()
{
    if test ! "$quiet"
    then
        echo "$*" 1>&2
    fi
    if test "$logfile"
    then
        echo "$*" >> "$logfile"
    fi
    if test "$syslog"
    then
        logger -t $(get_script_name) -p user.info "$*"
    fi
}

# XXX what if the message starts with a minus??
notice()
{
    echo "$*" 1>&2
    if test "$logfile"
    then
        echo "$*" >> "$logfile"
    fi
    if test "$syslog"
    then
        logger -t $(get_script_name) -p user.notice "$*"
    fi
    if test "$sms"
    then
        echo "$*" | sendsms ${phone}
    fi
}

# XXX what if the message starts with a minus??
warn()
{
    echo "$*" 1>&2
    if test "$logfile"
    then
        echo "$*" >> "$logfile"
    fi
    if test "$syslog"
    then
        logger -t $(get_script_name) -p user.warning "$*"
    fi
}

###
# RUNNING PROGRAMS

run()
{
    if test "$simulate"
    then
        info "Would run $@"
    else
        debug "Running $@"
        if test "$logfile"
        then
            #"$@" 2>&1 | tee -a "$logfile"
            2>&1 "$@" 2>&1 | tee -a "$logfile"
        else
            "$@"
        fi
    fi
}

silent()
{
    "$@" >/dev/null 2>/dev/null
}

###
# FILE MANIPULATION

# Return the directory part of a path.
get_directory_part()
{
    local location
    local dir

    location=$(get_location_part "$1")
    dir="${location%/*}"

    echo "$dir"
    return 0
}

# Get the amount of disk space used by a file or directory.
#
# Usage: get_size_of_file_or_directory <mount point or file>
# Returns: disk usage in kilobytes
get_size_of_file_or_directory()
{
    local size
    local file
    file="$1"
    size=$(du -ks "$file" | cut -f 1)
    if test $? -ne 0
    then
        error "Cannot determine disk usage of $file"
        return 1
    fi
    debug "$file uses $size kilobytes of disk space"
    echo "$size"
    return 0
}

# Get the free space in kilobytes of a file system.
#
# Usage: get_free_space_on_filesystem <mount point or file>
# Returns: free space in kilobytes
get_free_space_on_filesystem()
{
	(
    local tmpdir
    local dfout

    tmpdir=$(get_temporary_directory)
    dfout="$tmpdir"/df.$$
	trap 'test -n "$dfout" && rm "$dfout"' EXIT

    df -Pk "$tmpdir" > "$dfout"
    if test $? -ne 0
    then
        error "Cannot determine free disk space"
        exit 1
    fi

    i=0
    while read filesystem blocks used available capacity mountpoint
    do
        # skip header line, process the second line
        if test $i -ne 0
        then
            debug "$filesystem has $available kilobytes free"
            echo "$available"
            exit 0
        fi

        i=$((i + 1))
    done < "$dfout"
    error "Cannot determine free space on $filesystem"
    exit 1
	)
	return $?
}

# Return the filename part of a path.
get_filename_part()
{
    local location
    location=$(get_location_part "$1")
    echo "${location##/*/}"
    return 0
}

# Return the hostname from a remote path.
#
# Usage: get_hostname_part <hostname:/path/to/file>
# Returns: hostname
get_hostname_part()
{
    echo "$1" | cut -f 1 -d :
}

# Return the local part of a path
# get_location_part hostname:/path/to/file -> /path/to/file
get_location_part()
{
    echo "$1" | cut -f 2 -d :
}

# Return the path to the user's temporary directory.
get_temporary_directory()
{
    if test "$TMPDIR"
    then
        if test -d "$TMPDIR"
        then
            echo "$TMPDIR"
            return 0
        else
            debug "$TMPDIR does not exist, creating"
            mkdir "$TMPDIR"
            if test $? -eq 0
            then
                echo "$TMPDIR"
                return 0
            else
                error "Cannot create $TMPDIR, falling back to /tmp"
                if test -d /tmp
                then
                    if test -w /tmp
                    then
                        TMPDIR=
                        echo "/tmp"
                        return 0
                    else
                        error "/tmp is not writeable"
                        return 1
                    fi
                else
                    error "/tmp does not exist"
                    return 1
                fi
            fi
        fi
    elif test -d "$HOME/tmp"
    then
        if test -w "$HOME/tmp"
        then
            echo "$HOME/tmp"
            return 0
        else
            debug "$HOME/tmp is not writeable, falling back to /tmp"
            if test -d /tmp
            then
                if test -w /tmp
                then
                    echo "/tmp"
                    return 0
                else
                    error "/tmp is not writeable"
                    return 1
                fi
            else
                error "/tmp does not exist"
                return 1
            fi
        fi
    elif test -d /tmp
    then
        if test -w /tmp
        then
            echo "/tmp"
            return 0
        else
            error "/tmp is not writeable"
            return 1
        fi
    else
        error "/tmp does not exist"
        return 1
    fi
}

# whether a path is on a locally mounted file system or a remote SSH server
is_remote()
{
    echo "$1" | grep -q ":"
}

# add a line of text to the start of a file
prepend()
{
    line=$1

    file=$2
    if test ! -f "$file"
    then
        error "Cannot access $file"
        return 1
    fi

    tempfile="$file.$$.temp"
    if test -f "$tempfile"
    then
        error "$tempfile already exists"
        return 1
    fi

    echo "$line" > "$tempfile"

    if test $status -ne 0
    then
        error "Cannot store line in $tempfile"
        rm "$tempfile"
        return 1
    fi

    mergefile="$file.$$.merge"
    if test -f "$mergefile"
    then
        error "$mergefile already exists"
        return 1
    fi

    cat "$tempfile" "$file" > "$mergefile"
    mv "$file" "$file.bak"
    mv "$mergefile" "$file"
}

# add a line of text to the end of a file
append()
{
    line=$1

    file=$2
    if test ! -f "$file"
    then
        error "Cannot access $file"
        return 1
    fi

    echo "$line" >> "$file"
}


###
# NETWORKING

get_address_helper()
{
    local host
    local type
    local address
    local nameserver
    local tmpfile
    local tries

    host="$1"
    nameserver="$2"
    tmpfile="${tmpdir:-/tmp}/get_address_helper$$"
    tries=3

    debug "Resolving $host using ${nameserver:-default nameservers}"
    while test $tries -gt 0
    do
        host "${host}" ${nameserver} > "${tmpfile}"
        if test $? -eq 0
        then
            # read lines of the form
            # endbracket.net          A       203.214.81.131
            while read host type address
            do
                if test "${type}" = "A"
                then
                    echo "${address}"
					rm "${tmpfile}"
                    return 0
                fi
            done < "${tmpfile}"
        fi
        tries=$(($tries - 1))
    done
    error "Cannot resolve $host using $nameserver"
	rm "${tmpfile}"
    return 1
}


# get_address_of <hostname>
# Determine's the current IP address of a host.
get_address_of()
{
    local host
    local address
    local nameserver

    host="$1"

    # nameservers should be set elsewhere, e.g. in ~/.checkdns
    if test -n "${nameservers}"
    then
        debug "Getting address of ${host} using ${nameservers}"
        for nameserver in $nameservers
        do
            address=$(get_address_helper "${host}" ${nameserver})
            if test $? -eq 0
            then
                debug "Address of $host is $address"
                echo "${address}"
                return 0
            fi
        done
    else
        debug "Getting address of ${host} using default nameservers"
        address=$(get_address_helper "${host}")
        if test $? -eq 0
        then
            debug "Address of $host is $address"
            echo "${address}"
            return 0
        fi
    fi

    error "Cannot get address of ${host}"
    return 1
}

# Determine whether a host is up
host_up()
{
    local host
    host="$1"

    ping -c 3 $host >/dev/null
}

# XXX This doesn't test if the interface is up, only if it's configured
interface_up()
{
    local _temp
    local _status
    local _interface
    local _i
    _status=
    _interface="$1"
    _temp="$(get_temporary_directory)/network_up.$$"
    i=0

    netstat -i > "$_temp"
    cat $_temp
    if test $? -eq 0
    then
        i=0
        while read Iface MTU Met RXOK RXERR RXDRP RXOVR TXOK TXERR TXDRP TXOVR Flg
        do
            i=$(($i + 1))

            if test $i -eq 1
            then
                continue 
            fi

            if test -z "$Flg"
            then
                echo "Iface is $Iface"
                info "netstat output does not contain Flg field, assuming unsupported operating system"
                break
            fi
            if test "$Iface" = "$_interface"
            then
                if test "${Flg/U/}" != "${Flg}"
                then
                    _status=up
                else
                    _status=down
                fi
                debug "$_interface is $_status"
                break
            fi
        done < "$_temp"
    else
        warning "Cannot run netstat -i, falling back to less reliable ifconfig test"
    fi
    rm "$_temp"

    if test -z "$_status"
    then
        ifconfig $interface >/dev/null  # discard stdout, keep stderr
        if test $? -eq 0
        then
            info "$_interface is configured, assuming this means it's up"
            _status=up
        else
            info "Cannot get status of $_interface, assuming this means it's down"
            _status=down
        fi
    fi

    if test "$_status" = "up"
    then
        return 0
    else
        return 1
    fi
}

# whether we can get to the internet at the moment
internet_reachable()
{
    silent ping -c 3 google.com
}

###
# MISCELLANEOUS
# Return the name of the script that called this function.
# get_script_name
get_script_name()
{
    echo "${0##/*/}"
}

###
# STRING PROCESSING

# break <string> into words by splitting on delimiter <delim>
# Usage: split <delim> <string>
# Example: split , "foo,bar,baz"
split()
{
    if test $# -ne 2; then
        echo "Usage: split <delim> <string>" 1>&2
        return 1
    fi

    delim="$1"
    shift
    local IFS="$delim"
    local word
    for word in $1; do
        echo "$word"
    done
}
