scripts/bootstrap.sh

121 lines
2.1 KiB
Bash

#!/usr/bin/env bash
#
# Collection of reusable functions and variables
#
TODAY=`date`
HOSTNAME=`hostname`
function debug
{
if [ "${DEBUG}" = '1' ]; then
echo -e "DEBUG: $1"
fi
}
function err
{
echo -e "FATAL ERROR: $1"
exit 1
}
function warn
{
echo -e "WARNING: $1"
}
function validate_host
{
echo "$1" | grep -P '^(http|https):\/\/(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])(:[0-9]+)?$'
if [ $? -eq 0 ]; then
curl $1 > /dev/null 2>&1
fi
return $?
}
function validate_ip
{
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
function send_notification
{
opt=""
if [ -n "$FROM" ]; then
local mailcmd=$(readlink -f `which mail`)
if [ "${mailcmd}" = "/usr/bin/bsd-mailx" ]; then
opt="-a 'From: ${FROM}'"
else
opt="-r $FROM"
fi
fi
echo "Sending notification."
echo -e "$2" | mail $opt -s "$1" ${EMAIL}
}
function check_values
{
a_name=$1[@]
a_array=("${!a_name}")
if [ -z ${!a_name+x} ]; then
return
fi
if [ ${a_array[$2]} == true ]; then
if [ "x${4}" = 'x' ]; then
echo $3
exit 1
fi
fi
}
function run_cmd {
debug "Executing: '$1 $2'"
if [ ! -e $LOG ]; then
touch $LOG
fi
## Check if command exists on system
if ! command -v $1; then
err "$1: command not found"
fi
## Check if debug is set and send command output to shell
## Some commands send animated text that can corrupt the log
if test -n "${DEBUG}"; then
debug "DEBUG variable set, redirecting command output to console"
$1 $2
if [ $? -gt 0 ]; then
err "Failed running command '$1 $2'"
fi
else
$1 $2 2>> $LOG
# FIXME: This logic might need re-work?
if [ $? -gt 0 ]; then
echo "ERROR: Failed running command '$1 $2'."
echo "Displaying last 20 lines of ${LOG}..."
echo
tail $LOG
echo
exit 1
fi
fi
}