
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
RESET='\033[0m'

# Colored messages (blue is the default)
# Examples:
#   m "hello world"
#   m "hello world" "$GREEN"
function m () {
	local COLOR=${2:-$BLUE}
	echo -e "$COLOR$1$RESET"
}

function howlong () {
	/usr/bin/time --format='...took %e seconds' "$@"
}

function copy_function () {
	local ORIG_FUNC=$(declare -f $1)
	local NEWNAME_FUNC="$2${ORIG_FUNC#$1}"
	eval "$NEWNAME_FUNC"
}

function git_version () {
	VERSION=$(git -C "$ROOT" describe --tags --always 2> /dev/null || echo '')
	SHORT_VERSION=$(git -C "$ROOT" describe --tags --always --abbrev=0 2> /dev/null || echo '')
	REVISION=$(git -C "$ROOT" rev-parse HEAD 2> /dev/null || echo '')
	TIMESTAMP=$(date +"%Y-%m-%d %H:%M:%S %Z")
	GO_VERSION=$(go version | { read _ _ v _; echo ${v#go}; })
}

function rust_host () {
    rustc --version --verbose | sed -n 's|host: ||p'
}

function cargo_examples () {
    cargo run --example 2>&1 | grep --extended-regexp '^    ' | sort
}

function into_python () {
    m "using Python virtual environment: $PYTHON_VENV"
    . "$PYTHON_VENV/bin/activate"
}

function only_root () {
    if [ "$EUID" -ne 0 ]; then
        m "Run this script as root" "$RED"
        exit 1
    fi
}

function not_root () {
    if [ "$EUID" == 0 ]; then
        m "Do not run this script as root" "$RED"
        exit 1
    fi
}
