Updates util scripts

This commit is contained in:
Alicia Sykes 2022-09-01 19:45:56 +01:00
parent c8a1548c02
commit f26fafc2df
6 changed files with 79 additions and 353 deletions

10
utils/am-i-online.sh Normal file → Executable file
View File

@ -19,7 +19,7 @@ function aio_check-dns() {
# Checks if can ping default getway
function aio_ping-gateway() {
ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && \
ping -q -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && \
echo -e "${pre_success} Gateway Availible${post_string}" || \
echo -e "${pre_failure} Gateway Unavailible${post_string}"
}
@ -37,9 +37,11 @@ function aio_check-url() {
# Checks there are network interfaces
function aio_check-interfaces() {
for interface in $(ls /sys/class/net/ | grep -v lo); do
if [[ $(cat /sys/class/net/$interface/carrier) = 1 ]]; then OnLine=1; fi
done
if [[ -d /sys/class/net/ ]]; then
for interface in $(ls /sys/class/net/ | grep -v lo); do
if [[ $(cat /sys/class/net/$interface/carrier) = 1 ]]; then OnLine=1; fi
done
fi
if ! [ $OnLine ]; then
echo -e "${pre_failure} Interfaces not Configured${post_string}"
else

50
utils/color-map.sh Executable file
View File

@ -0,0 +1,50 @@
#!/bin/bash
# Utilities for checking terminal color support, and printing color pallete
TEXT_COL="\033[1;30m"
RESET='\033[0m'
# Outputs the number of colors supported by your terminal emulator
function check_color_support () {
echo -e "\n${TEXT_COL}Your terminal supports $(tput colors) colors."
}
# Prints main 16 colors
function color_map_16_bit () {
echo -e "\n${TEXT_COL}16-Bit Pallete${RESET}\n"
base_colors='40m 41m 42m 43m 44m 45m 46m 47m'
for BG in $base_colors; do echo -en "$EINS \033[$BG \033[0m"; done; echo
for BG in $base_colors; do echo -en "$EINS \033[1;30m\033[$BG $(echo $BG) \033[0m"; done; echo
for BG in $base_colors; do echo -en "$EINS \033[$BG \033[0m"; done; echo
}
# Prints all 256 supported colors
function color_map_256_bit () {
echo -e "\n${TEXT_COL}256-Bit Pallete${RESET}\n"
for i in {0..255}; do printf '\e[38;5;%dm%3d ' $i $i; (((i+3) % 18)) || printf '\e[0m\n'; done
echo
}
# Executes Python script by @grawity for interactivley selecting colors
function color_chooser () {
curl -s https://raw.githubusercontent.com/grawity/code/master/term/xterm-color-chooser | python3
}
# Determine if file is being run directly or sourced
([[ -n $ZSH_EVAL_CONTEXT && $ZSH_EVAL_CONTEXT =~ :file$ ]] ||
[[ -n $KSH_VERSION && $(cd "$(dirname -- "$0")" &&
printf '%s' "${PWD%/}/")$(basename -- "$0") != "${.sh.file}" ]] ||
[[ -n $BASH_VERSION ]] && (return 0 2>/dev/null)) && sourced=1 || sourced=0
# If script being called directly run immediatley, otherwise register aliases
if [ $sourced -eq 0 ]; then
check_color_support
color_map_16_bit
color_map_256_bit
else
alias color-map-16="color_map_16_bit"
alias color-map-256="color_map_256_bit"
alias color-map="color_map_16_bit && color_map_256_bit"
alias color-support="check_color_support"
fi

View File

@ -1,20 +0,0 @@
#!/bin/bash
# Prints each foreground and background color using standard 16-bit pallete
# Based on: https://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
T='Hi!' # The test text
echo -e "\n \t\t40m\t 41m\t 42m\t 43m\t 44m\t 45m\t 46m\t 47m";
for FGs in ' m' ' 1m' ' 30m' '1;30m' ' 31m' '1;31m' ' 32m' \
'1;32m' ' 33m' '1;33m' ' 34m' '1;34m' ' 35m' '1;35m' \
' 36m' '1;36m' ' 37m' '1;37m';
do FG=${FGs// /}
echo -en " $FGs \033[$FG $T "
for BG in 40m 41m 42m 43m 44m 45m 46m 47m;
do echo -en "$EINS \033[$FG\033[$BG $T \033[0m";
done
echo;
done
echo

315
utils/test.sh Normal file → Executable file
View File

@ -1,315 +0,0 @@
#!/usr/bin/env bash
SCRIPTNAME="$0"
VERSION="0.0.1"
SCRIPTS_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )"
source "$SCRIPTS_DIR/util/base.sh"
source "$SCRIPTS_DIR/util/logging.sh"
source "$SCRIPTS_DIR/util/config.sh"
source "$SCRIPTS_DIR/util/api.sh"
source "$SCRIPTS_DIR/util/dns.sh"
REQUIRES_FUNCS \
debug info warn error log_start \
config_load_all config_validate \
merge_arrays repeated
# shellcheck disable=SC2034
HELP_TEXT="
$SCRIPTNAME v$VERSION
Helper script to update a DNS record on multiple providers.
Usage:
$SCRIPTNAME --domain=domain.example.com [--get|--set=value] [...options]
Options:
[domain] The DNS domain you want to get or set (required)
--domain=example.com Same as passing [domain] directly as an argument
-t=|--type=A The DNS record type, e.g. A, CNAME, etc. (A default)
-g|--get Get the record value (the default)
-s=|--set=value Set the record value, e.g. 123.235.324.234 or the
special value 'pubip' to use current public ip
-l=|--ttl=n Set the record TTL to n seconds (overrides api default)
-p=|--proxied Set the record to be proxied through CDN (Cloudflare only)
-a=|--api=cf,do List of DNS providers to use, e.g. all (default) or cf,do
-r=|--refresh=n Run continusouly every n seconds in a loop
-w=|--timeout=n Wait n seconds before aborting and retrying
-c=|--config=file Path to a dotenv-formatted config file to load
-e=|--config-prefix=X Load config vars with prefix X e.g. X_VERBOSE=1
-h|--help Show this help message
-v|--verbose Show more verbose output
-q|--quiet Supress all output except for errors and warnings
--color Force showing of colors in the stderr output
--nocolor Force hiding of colors in the stderr output
--notimestamps Force hiding of timestamps in stderr output
--nologlevels Force hiding of log levels in stderr output
Config: (passed via --config=file or environment variables)
DOMAIN=a.example.com Same as --domain option
CF_API_KEY=12345 Clouflare API token: https://dash.cloudflare.com/<account_id>/profile/api-tokens
DO_API_KEY=12345 DigitalOcean API token: https://cloud.digitalocean.com/account/api/tokens
VEBOSE=1 Show debug output [0]/1
QUIET=0 Hide info output: [0]/1
COLOR=1 Colorize stderr output: [1]/0
TIMEOUT=15 Seconds to wait before aborting and retrying
Examples:
$SCRIPTNAME abc.example.com
$SCRIPTNAME abc.example.com --get --refresh=30
$SCRIPTNAME abc.example.com --type=A --set=pubip --ttl=300 --api=digitalocean --config=~/.digitalocean.env
$SCRIPTNAME --domain=abc.example.com --type=A --set=1.2.3.4 --api=digitalocean,cloudflare --refresh=30 --config=./secrets.env
"
### Default Config
API_KEY_PLACEHOLDER="set-this-value-in-your-config-file"
ALLOWED_APIS='cf,do'
# shellcheck disable=SC2034
declare -A DNS_CLI_ARGS=(
# Flag Arguments
[GET]='-g|--get'
[PROXIED]='-p|--proxied'
# Named Arguments
[DOMAIN]='-d|--domain|-d=*|--domain=*'
[TYPE]='-t|--type|-t=*|--type=*'
[SET]='-s|--set|-s=*|--set=*'
[TTL]='-l|-l=*|--ttl|--ttl=*'
[API]='-a|-a=*|--api|--api=*'
# Positional Arguments
# [DOMAIN]='*'
# [TYPE]='*'
# [SET]='*'
)
merge_arrays CLI_ARGS BASE_CLI_ARGS DNS_CLI_ARGS
# shellcheck disable=SC2034
declare -A DNS_CONFIG_DEFAULTS=(
[DOMAIN]=''
[TYPE]='A'
[GET]=''
[SET]=''
[API]='all'
[TTL]='default'
[PROXIED]='false'
[CF_API_KEY]="$API_KEY_PLACEHOLDER"
[CF_DEFAULT_TTL]=1
[DO_API_KEY]="$API_KEY_PLACEHOLDER"
[DO_DEFAULT_TTL]=300
)
merge_arrays CONFIG_DEFAULTS BASE_CONFIG_DEFAULTS DNS_CONFIG_DEFAULTS
declare -A CONFIG
# shellcheck disable=SC2016 disable=SC2034
declare -A CONFIG_VALIDATORS=(
[DOMAIN]='[[ "${CONFIG[DOMAIN]}" ]]'
[TYPE]='[[ "${CONFIG[TYPE]}" ]]'
[SET]='validate_set_config'
[API]='validate_api_config'
)
merge_arrays CONFIG_VALIDATORS BASE_CONFIG_VALIDATORS DNS_CONFIG_VALIDATORS
function validate_set_config {
if [[ ! "${CONFIG[GET]}" && ! "${CONFIG[SET]}" ]]; then
fatal "Missing --get or --set=value argument (pass --help for usage and examples)."
fi
if [[ "${CONFIG[SET]}" && "${CONFIG[TYPE]}" == 'A' ]]; then
if ! [[ "${CONFIG[SET]}" == 'pubip' ]] || echo "${CONFIG[SET]}" | grep -q "$IPV4_REGEX"; then
error "Invalid value --set=${CONFIG[SET]} must be pubip or an ip address"
return 1
fi
fi
return 0
}
function validate_api_config {
local APIS="${CONFIG[API]}"
for API in ${APIS//,/ }; do
case "$API" in
'digitalocean'|'do')
[[ "${CONFIG[DO_API_KEY]}" == "$API_KEY_PLACEHOLDER" ]] && {
error "You must pass your DO_API_KEY via environment variable or --config=file.env (pass --help for more info)."
return 1
}
;;
'cloudflare'|'cf')
[[ "${CONFIG[CF_API_KEY]}" == "$API_KEY_PLACEHOLDER" ]] && {
error "You must pass your CF_API_KEY via environment variable or --config=file.env (pass --help for more info)."
return 1
}
;;
'all')
CONFIG[API]="$ALLOWED_APIS"
;;
*)
error "Unrecognized API type '$API'. (must be one or more of: $ALLOWED_APIS)"
return 1
;;
esac
done
return 0
}
### Main Functions
function get_record {
local API="$1" DOMAIN="$2" TYPE="$3"
if [[ "$API" == "do" ]]; then
. ./lib/digitalocean.sh
elif [[ "$API" == "cf" ]]; then
. ./lib/cloudflare.sh
fi
dns_get_record "$DOMAIN" "$TYPE"
}
function update_record {
local API="$1" DOMAIN="$2" TYPE="$3" VALUE="$4" TTL="$5" PROXIED="$6"
local VALUE_BEFORE VALUE_AFTER STATUS
[[ "$VALUE" == "pubip" ]] && VALUE="$(get_public_ip)" # replace pubip with actual ip
if [[ "$TYPE" == "TXT" ]]; then
VALUE="$(echo "$VALUE" | perl -pe 's/\n/\\\n/gm')"
fi
if [[ "$API" == "do" ]]; then
. ./lib/digitalocean.sh
elif [[ "$API" == "cf" ]]; then
. ./lib/cloudflare.sh
fi
VALUE_BEFORE="$(
dns_get_record \
"$DOMAIN" \
"$TYPE"
)" && STATUS="$?" || STATUS="$?"
if [[ "$STATUS" == "8" ]]; then
warn "$API/$DOMAIN/$TYPE=$VALUE creating new record..."
VALUE_AFTER="$(
dns_create_record \
"$DOMAIN" \
"$TYPE" \
"$VALUE" \
"$TTL" \
"$PROXIED"
)"
elif ((STATUS>0)); then
fatal --status=$STATUS "dns_get_record return an invalid exit status $STATUS"
elif [[ "$VALUE_BEFORE" == "$VALUE" ]]; then
info "$API/$DOMAIN/$TYPE=$VALUE_BEFORE is up-to-date."
return 0
else
info "$API/$DOMAIN/$TYPE=$VALUE_BEFORE updating to $VALUE..."
VALUE_AFTER="$(
dns_set_record \
"$DOMAIN" \
"$TYPE" \
"$VALUE" \
"$TTL" \
"$PROXIED"
)"
fi
if ! [[ "$VALUE_AFTER" == "$VALUE" || "$VALUE_AFTER" == "${VALUE}." ]]; then
error "$API/$DOMAIN/$TYPE=$VALUE update failed (got ${VALUE_AFTER:-API error})."
return 1
else
info "$API/$DOMAIN/$TYPE=$VALUE update succeeded."
return 0
fi
}
function log_start_dns {
config_assert INTERVAL API DOMAIN TYPE
local INTERVAL_STR
# Begin check/update process
((CONFIG[INTERVAL]>0)) && INTERVAL_STR="every ${CONFIG[INTERVAL]}s" || INTERVAL_STR="once"
if [[ "${CONFIG[SET]}" ]]; then
info "Starting: SET ${CONFIG[API]}/${CONFIG[DOMAIN]}/${CONFIG[TYPE]}=${CONFIG[SET]} $INTERVAL_STR..."
else
info "Starting: GET ${CONFIG[API]}/${CONFIG[DOMAIN]}/${CONFIG[TYPE]} $INTERVAL_STR..."
fi
}
function runloop {
local APIS="${CONFIG[API]}"
GET="${CONFIG[GET]}"
SET="${CONFIG[SET]}"
for API in ${APIS//,/ }; do
if ((GET==1)); then
timed "${CONFIG[TIMEOUT]}" \
get_record \
"$API" \
"${CONFIG[DOMAIN]}" \
"${CONFIG[TYPE]}"
return $?
elif [[ "$SET" ]]; then
timed "${CONFIG[TIMEOUT]}" \
update_record \
"$API" \
"${CONFIG[DOMAIN]}" \
"${CONFIG[TYPE]}" \
"${CONFIG[SET]}" \
"${CONFIG[TTL]}" \
"${CONFIG[PROXIED]}"
return $?
else
fatal 'You must pass either --get or --set=value'
fi
done
}
function main {
# Load config from file, env variables, and kwargs
config_load_all CONFIG_DEFAULTS CLI_ARGS "$@"
config_validate CONFIG_VALIDATORS
log_start_dns
repeated "${CONFIG[INTERVAL]}" runloop
}
main "$@"
#wait "$!" && STATUS=$? || STATUS=$?
#jobs -p >/dev/null 2>&1
#jobs -p | xargs 'kill -9 --' >/dev/null 2>&1
#if ((STATUS>125)); then
# codes >= 125 are used by the shell only and cannot be returned from scripts
# https://www.tldp.org/LDP/abs/html/exitcodes.html
# exit $((STATUS-100))
#else
# exit $STATUS
#fi

34
utils/transfer.sh Normal file → Executable file
View File

@ -5,46 +5,54 @@
# Can be either source'd then call`transfer` function, or invoked directly
# Licensed under MIT, (C) Alicia Sykes 2022: https://aliciasykes.com
# Once upload is complete, checks response is correct and prints to console
output_secret_link() {
echo -e "\033[1;96m\nTransfer Complete 📤\033[0m"
echo -e "\033[4;36m${1}\033[0m"
}
# Uploads file to file share service
transfer-file () {
curl --upload-file $1 $FILE_TRANSFER_SERVICE
transfer_file () {
output_secret_link $(curl --upload-file $1 $FILE_TRANSFER_SERVICE)
}
# Combines files into an archive, uploads it, then removes
transfer-files () {
transfer_files () {
zip $TMP_FILE $@
curl --upload-file $TMP_FILE $FILE_TRANSFER_SERVICE
output_secret_link $(curl --upload-file $TMP_FILE $FILE_TRANSFER_SERVICE)
rm $TMP_FILE
}
# Zips directory up, uploads it, then removes it
transfer-directory () {
transfer_directory () {
zip -r $TMP_FILE $1
curl --upload-file $TMP_FILE $FILE_TRANSFER_SERVICE
output_secret_link $(curl --upload-file $TMP_FILE $FILE_TRANSFER_SERVICE)
rm $TMP_FILE
}
# Determine the type of transfer, and call appropriate function
transfer () {
FILE_TRANSFER_SERVICE="${FILE_TRANSFER_SERVICE:=https://transfer.sh}"
if [[ $@ == *"--help" ]] transfer-help && return
if [[ $@ == *"--help" ]]; then
transfer_help && return
fi
TMP_FILE="/tmp/file-transfer-$(date +%s).zip"
if [ -z "$1" ]; then
transfer-help
transfer_help
return
fi
if [[ -f $1 ]] && [ "$#" -eq 1 ]; then
transfer-file $@
transfer_file $@
elif [ -d $1 ] && [ "$#" -eq 1 ]; then
transfer-directory $@
transfer_directory $@
elif [ "$#" -gt 1 ]; then
transfer-files $@
transfer_files $@
fi
unset TMP_FILE
}
# Shows usage instructions
transfer-help () {
transfer_help () {
welcome_msg="\033[1;33mHelper script for transfering files via transfer.sh\n"
welcome_msg="$welcome_msg\033[0;33mInvoke script with file(s) or a directory to upload\n"
welcome_msg="$welcome_msg\033[1;33mE.g.\033[0;93m\n $ transfer hello.txt\n"
@ -61,7 +69,7 @@ transfer-help () {
# If script being called directly, invoke transfer or show help
if [ $sourced -eq 0 ]; then
if [ ! -n "${1+set}" ] || [[ $@ == *"--help"* ]]; then
transfer-help
transfer_help
else
transfer $@
fi

View File

@ -11,7 +11,7 @@ source ${zsh_dir}/aliases/general.zsh
source ${zsh_dir}/aliases/git.zsh
source ${zsh_dir}/aliases/node-js.zsh
source ${zsh_dir}/aliases/flutter.zsh
source ${zsh_dir}/aliases/alias-tips.zsh
# source ${zsh_dir}/aliases/alias-tips.zsh
# Setup Antigen, and import plugins
source ${zsh_dir}/helpers/setup-antigen.zsh
@ -35,6 +35,7 @@ source ${utils_dir}/hr.sh
source ${utils_dir}/web-search.sh
source ${utils_dir}/am-i-online.sh
source ${utils_dir}/welcome-banner.sh
source ${utils_dir}/color-map.sh
# Left over tasks
source ${zsh_dir}/helpers/misc-stuff.zsh