shell-base/script

97 lines
1.6 KiB
Plaintext
Raw Normal View History

2023-01-02 11:00:26 +01:00
#!/bin/sh
2023-05-21 14:56:42 +02:00
set -eu
2023-01-02 11:00:26 +01:00
usage() {
2023-05-21 15:27:36 +02:00
printf "Usage: %s [-l DEBUG_LEVEL] [-h]\n" "$0"
2023-01-08 15:18:23 +01:00
}
help() {
cat << EOH
SYNOPSIS
2023-05-21 15:27:36 +02:00
$0 [-l DEBUG_LEVEL] [-h]
2023-01-08 15:18:23 +01:00
DESCRIPTION
$0 does things!
OPTIONS
-h Show this help
2023-05-21 15:20:15 +02:00
2023-05-21 15:27:36 +02:00
-l debug|info|notice|warning|error
Debug level
2023-01-08 15:18:23 +01:00
EOH
2023-01-02 11:00:26 +01:00
}
on_interrupt() {
2023-05-21 15:56:04 +02:00
log -l notice ""
log -l notice "Process aborted!"
2023-01-02 11:00:26 +01:00
exit 130
}
main() {
2023-05-21 15:20:15 +02:00
while getopts "l:h" option; do
2023-01-02 11:00:26 +01:00
case "${option}" in
2023-01-08 15:18:23 +01:00
h) help; exit 0;;
2023-05-21 15:20:15 +02:00
l) LOG_VERBOSE="$OPTARG";;
2023-05-21 14:56:42 +02:00
?) log -l error "$(usage)"; exit 1;;
2023-01-02 11:00:26 +01:00
esac
done
2023-05-21 15:20:15 +02:00
# log [-t] [-l debug|info|notice|warning|error] message
2023-05-21 14:56:42 +02:00
2023-01-02 11:00:26 +01:00
exit 0
}
2023-05-21 14:56:42 +02:00
log() {
2023-05-21 18:27:33 +02:00
LOG_VERBOSE="${LOG_VERBOSE:-info}"
2023-05-21 14:56:42 +02:00
LEVEL=info
TIME=
while getopts "tl:" option; do
case "${option}" in
l) LEVEL="$OPTARG"; shift $((OPTIND-1));;
2023-05-21 18:18:10 +02:00
t) TIME="$(printf "[%s] " "$(date +'%Y-%m-%dT%H:%M:%S.%s')")"; shift $((OPTIND-1));;
2023-05-21 14:56:42 +02:00
*) exit 1;;
esac
done
if [ -t 2 ] && [ -z "${NO_COLOR-}" ]; then
case "${LEVEL}" in
2023-05-21 18:27:33 +02:00
debug) COLOR="$(tput setaf 3)";;
notice) COLOR="$(tput setaf 4)";;
warning) COLOR="$(tput setaf 5)";;
error) COLOR="$(tput setaf 1)";;
*) COLOR="$(tput sgr0)";;
2023-05-21 14:56:42 +02:00
esac
fi
2023-05-21 18:27:33 +02:00
case "${LEVEL}" in
debug) LEVEL=100;;
notice) LEVEL=250;;
warning) LEVEL=300;;
error) LEVEL=400;;
*) LEVEL=200;;
esac
2023-05-21 15:20:15 +02:00
case "${LOG_VERBOSE}" in
debug) LOG_VERBOSE_VALUE=100;;
notice) LOG_VERBOSE_VALUE=250;;
warning) LOG_VERBOSE_VALUE=300;;
error) LOG_VERBOSE_VALUE=400;;
*) LOG_VERBOSE_VALUE=200;;
esac
if [ $LEVEL -ge $LOG_VERBOSE_VALUE ]; then
2023-05-21 15:56:04 +02:00
printf "%s\n" "$*" | while IFS='' read -r LINE; do
printf "%s%s%s\n" "${COLOR:-}" "${TIME:-}" "$LINE" >&2
done
2023-05-21 15:20:15 +02:00
fi
2023-05-21 14:56:42 +02:00
}
2023-01-02 11:00:26 +01:00
trap on_interrupt INT
main "$@"