Config, removed tmux, removed util functions

This commit is contained in:
Leon Radeck committed 2018-02-10 06:50:44 +01:00
1 parent 729ccd7e31
commit b60777fff8
4 files changed
+13 -461

No files matched your search

@@ -59,14 +59,20 @@ logFile="$HOME/Library/Logs/${scriptBasename}.log"
function mainScript() {
echo -n
require_region
local resource_file=./lib/resources-$region.sh
local config_file=~/.aws-automation/config-$region
if is_exists ${resource_file}; then
source "${resource_file}"
fi
if is_exists ${config_file}; then
source "${config_file}"
fi
init_resources
safeExit
if $instance; then
instance_start
@@ -148,33 +148,19 @@ function init_resources(){
update_resources $resources_file
fi
update_configuration
if ! is_exists ~/.aws-automation/config-$region; then
create_configuration
fi
}
function update_configuration(){
function create_configuration(){
mkdir -p ~/.aws-automation
touch ~/.aws-automation/config-$region
init_config_variable default_key_name
init_config_variable default_key_file
init_config_variable default_mongodb_host
init_config_variable default_mongodb_port
init_config_variable default_region
init_config_variable default_instance_type
init_config_variable default_server_startup_notify
init_config_variable default_new_admin_password
init_config_variable default_user_username
init_config_variable default_user_password
config=$(build_configuration "default_key_name=" "default_key_file=" "default_mongodb_host=" "default_mongodb_port=" "default_region="\
"default_instance_type=" "default_server_startup_notify=" "default_new_admin_password=" "default_user_username=" "default_user_password=")
}
function init_config_variable(){
local tmp=$(get_config_variable "$1")
if [ -z $tmp ]; then
set_config_variable "$1" ""
else
read -r "$1" <<< $tmp
fi
echo $config > ~/.aws-automation/config-$region
}
function set_config_variable(){
@@ -1,108 +0,0 @@
#!/usr/bin/env bash
# -----------------------------------------------------------
# Construct tmux user interface
# -----------------------------------------------------------
function construct_ui() {
# enable scrolling, clicking on panes etc.
tmux set -g mouse on
# enable named border at the top of panes
tmux set -g pane-border-status top
tmux set -g pane-border-format " [#{pane_index}] - #T "
# close all panes except one
reset_panes
sleep 1
# construct pane layout
tmux split-window -h -p 50
tmux select-pane -t 0
tmux split-window -v -p 50
tmux select-pane -t 2
tmux split-window -v -p 50
tmux select-pane -t 0
}
# -----------------------------------------------------------
# Opens ssh connections on all three panes
# @param $1 ssh user
# @param $2 dns name of instance
# -----------------------------------------------------------
function open_connections() {
# Can't use ssh wrapper at this point because function cannot be export within tmux environment.
if [ -z $key_file ]; then
command="ssh -o StrictHostKeyChecking=no $1@$2"
else
command="ssh -o StrictHostKeyChecking=no -i $key_file $1@$2"
fi
# Send $command to all three panes and execute
tmux send-keys -t 1 $command C-m
tmux send-keys -t 2 $command C-m
tmux send-keys -t 3 $command C-m
}
# -----------------------------------------------------------
# Close all panes except first
# -----------------------------------------------------------
function reset_panes(){
if more_panes_are_open; then
tmux kill-pane -a -t 0
fi
}
function get_number_of_panes(){
tmux display-message -p '#{window_panes}'
}
function more_panes_are_open(){
if inside_tmux_session; then
if [ "$(get_number_of_panes)" -gt 1 ]; then
return 0;
fi
fi
return 1;
}
function check_if_tmux_is_used(){
check_dependencies
check_environment
}
function check_dependencies() {
if ! is_tmux_available; then
echo "The package \"tmux\" is required to run the script with this option"
safeExit
fi
}
function check_environment() {
if ! inside_tmux_session; then
echo "Please run this script inside a tmux session. To do so enter \"tmux\" into the console and start the script from there."
safeExit
fi
}
function is_tmux_available(){
type tmux >/dev/null 2>/dev/null
}
function inside_tmux_session(){
[ "$TERM" = "screen" ] && [ -n "$TMUX" ]
}
# -----------------------------------------------------------
# Prompts user if open panes should be closed
# -----------------------------------------------------------
function confirm_reset_panes(){
if more_panes_are_open; then
seek_confirmation "Do you want to close all open panes?"
if is_confirmed; then
reset_panes
else
safeExit
fi
fi
}
@@ -265,41 +265,6 @@ function is_not_empty() {
return 1
}
# Test whether a command exists
# ------------------------------------------------------
# Usage:
# if type_exists 'git'; then
# some action
# else
# some other action
# fi
# ------------------------------------------------------
function type_exists() {
if [ "$(type -P "$1")" ]; then
return 0
fi
return 1
}
function type_not_exists() {
if [ ! "$(type -P "$1")" ]; then
return 0
fi
return 1
}
# Test which OS the user runs
# $1 = OS to test
# Usage: if is_os 'darwin'; then
function is_os() {
if [[ "${OSTYPE}" == $1* ]]; then
return 0
fi
return 1
}
# SEEKING CONFIRMATION
# ------------------------------------------------------
@@ -395,16 +360,6 @@ function pauseScript() {
fi
}
function in_array() {
# Determine if a value is in an array.
# Usage: if in_array "VALUE" "${ARRAY[@]}"; then ...
local value="$1"; shift
for arrayItem in "$@"; do
[[ "${arrayItem}" == "${value}" ]] && return 0
done
return 1
}
# Text Transformations
# -----------------------------------
# Transform text using these functions.
@@ -418,13 +373,6 @@ lower() {
tr '[:upper:]' '[:lower:]'
}
upper() {
# Convert stdin to uppercase.
# usage: text=$(upper <<<"$1")
# echo "MAKETHISUPPERCASE" | upper
tr '[:lower:]' '[:upper:]'
}
function lower_trim(){
echo $1 | lower | trim
}
@@ -434,242 +382,10 @@ trim() {
tr -d '[:space:]'
}
ltrim() {
# Removes all leading whitespace (from the left).
local char=${1:-[:space:]}
sed "s%^[${char//%/\\%}]*%%"
}
rtrim() {
# Removes all trailing whitespace (from the right).
local char=${1:-[:space:]}
sed "s%[${char//%/\\%}]*$%%"
}
lttrim() {
# Removes all leading/trailing whitespace
# Usage examples:
# echo " foo bar baz " | trim #==> "foo bar baz"
ltrim "$1" | rtrim "$1"
}
only_letters_and_numbers(){
tr -d -c '[:alnum:]'
}
squeeze() {
# Removes leading/trailing whitespace and condenses all other consecutive
# whitespace into a single space.
#
# Usage examples:
# echo " foo bar baz " | squeeze #==> "foo bar baz"
local char=${1:-[[:space:]]}
sed "s%\(${char//%/\\%}\)\+%\1%g" | trim "$char"
}
squeeze_lines() {
# <doc:squeeze_lines> {{{
#
# Removes all leading/trailing blank lines and condenses all other
# consecutive blank lines into a single blank line.
#
# </doc:squeeze_lines> }}}
sed '/^[[:space:]]\+$/s/.*//g' | cat -s | trim_lines
}
progressBar() {
# progressBar
# -----------------------------------
# Prints a progress bar within a for/while loop.
# To use this function you must pass the total number of
# times the loop will run to the function.
#
# usage:
# for number in $(seq 0 100); do
# sleep 1
# progressBar 100
# done
# -----------------------------------
if [[ "${quiet}" = "true" ]] || [ "${quiet}" == "1" ]; then
return
fi
local width
width=30
bar_char="#"
# Don't run this function when scripts are running in verbose mode
if ${verbose}; then return; fi
# Reset the count
if [ -z "${progressBarProgress}" ]; then
progressBarProgress=0
fi
# Do nothing if the output is not a terminal
if [ ! -t 1 ]; then
echo "Output is not a terminal" 1>&2
return
fi
# Hide the cursor
tput civis
trap 'tput cnorm; exit 1' SIGINT
if [ ! "${progressBarProgress}" -eq $(( $1 - 1 )) ]; then
# Compute the percentage.
perc=$(( progressBarProgress * 100 / $1 ))
# Compute the number of blocks to represent the percentage.
num=$(( progressBarProgress * width / $1 ))
# Create the progress bar string.
bar=
if [ ${num} -gt 0 ]; then
bar=$(printf "%0.s${bar_char}" $(seq 1 ${num}))
fi
# Print the progress bar.
progressBarLine=$(printf "%s [%-${width}s] (%d%%)" "Running Process" "${bar}" "${perc}")
echo -en "${progressBarLine}\r"
progressBarProgress=$(( progressBarProgress + 1 ))
else
# Clear the progress bar when complete
echo -ne "${width}%\033[0K\r"
unset progressBarProgress
fi
tput cnorm
}
htmlDecode() {
# Decode HTML characters with sed
# Usage: htmlDecode <string>
echo "${1}" | sed -f "${SOURCEPATH}/htmlDecode.sed"
}
htmlEncode() {
# Encode HTML characters with sed
# Usage: htmlEncode <string>
echo "${1}" | sed -f "${SOURCEPATH}/htmlEncode.sed"
}
urlencode() {
# URL encoding/decoding from: https://gist.github.com/cdown/1163649
# Usage: urlencode <string>
local length="${#1}"
for (( i = 0; i < length; i++ )); do
local c="${1:i:1}"
case $c in
[a-zA-Z0-9.~_-]) printf "%s" "$c" ;;
*) printf '%%%02X' "'$c"
esac
done
}
urldecode() {
# Usage: urldecode <string>
local url_encoded="${1//+/ }"
printf '%b' "${url_encoded//%/\x}"
}
parse_yaml() {
# Function to parse YAML files and add values to variables. Send it to a temp file and source it
# https://gist.github.com/DinoChiesa/3e3c3866b51290f31243 which is derived from
# https://gist.github.com/epiloque/8cf512c6d64641bde388
#
# Usage:
# $ parse_yaml sample.yml > /some/tempfile
#
# parse_yaml accepts a prefix argument so that imported settings all have a common prefix
# (which will reduce the risk of name-space collisions).
#
# $ parse_yaml sample.yml "CONF_"
local prefix=$2
local s
local w
local fs
s='[[:space:]]*'
w='[a-zA-Z0-9_]*'
fs="$(echo @|tr @ '\034')"
sed -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
-e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
awk -F"$fs" '{
indent = length($1)/2;
if (length($2) == 0) { conj[indent]="+";} else {conj[indent]="";}
vname[indent] = $2;
for (i in vname) {if (i > indent) {delete vname[i]}}
if (length($3) > 0) {
vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
printf("%s%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, conj[indent-1],$3);
}
}' | sed 's/_=/+=/g'
}
httpStatus() {
# -----------------------------------
# Shamelessly taken from: https://gist.github.com/rsvp/1171304
#
# Usage: httpStatus URL [timeout] [--code or --status] [see 4.]
# ^message with code (default)
# ^code (numeric only)
# ^in secs (default: 3)
# ^URL without "http://" prefix works fine.
#
# 4. curl options: e.g. use -L to follow redirects.
#
# Dependencies: curl
#
# Example: $ httpStatus bit.ly
# 301 Redirection: Moved Permanently
#
# Example: $ httpStatus www.google.com 100 -c
# 200
#
# -----------------------------------
local curlops
local arg4
local arg5
local arg6
local arg7
local flag
local timeout
local url
saveIFS=${IFS}
IFS=$' \n\t'
url=${1}
timeout=${2:-'3'}
# ^in seconds
flag=${3:-'--status'}
# curl options, e.g. -L to follow redirects
arg4=${4:-''}
arg5=${5:-''}
arg6=${6:-''}
arg7=${7:-''}
curlops="${arg4} ${arg5} ${arg6} ${arg7}"
# __________ get the CODE which is numeric:
code=`echo $(curl --write-out %{http_code} --silent --connect-timeout ${timeout} \
--no-keepalive ${curlops} --output /dev/null ${url})`
# __________ get the STATUS (from code) which is human interpretable:
status=$(get_http_code_message $code)
# _______________ MAIN
case ${flag} in
--status) echo "${code} ${status}" ;;
-s) echo "${code} ${status}" ;;
--code) echo "${code}" ;;
-c) echo "${code}" ;;
*) echo " !! httpstatus: bad flag" && safeExit;;
esac
IFS="${saveIFS}"
}
function get_http_code_message(){
case $1 in
@@ -719,51 +435,3 @@ function get_http_code_message(){
esac
echo "$status"
}
function makeCSV() {
# Creates a new CSV file if one does not already exist.
# Takes passed arguments and writes them as a header line to the CSV
# Usage 'makeCSV column1 column2 column3'
# Set the location and name of the CSV File
if [ -z "${csvLocation}" ]; then
csvLocation="${HOME}/Desktop"
fi
if [ -z "${csvName}" ]; then
csvName="$(LC_ALL=C date +%Y-%m-%d)-${FUNCNAME[1]}.csv"
fi
csvFile="${csvLocation}/${csvName}"
# Overwrite existing file? If not overwritten, new content is added
# to the bottom of the existing file
if [ -f "${csvFile}" ]; then
seek_confirmation "${csvFile} already exists. Overwrite?"
if is_confirmed; then
rm "${csvFile}"
writeCSV "$@"
fi
fi
}
function writeCSV() {
# Takes passed arguments and writes them as a comma separated line
# Usage 'writeCSV column1 column2 column3'
csvInput=($@)
saveIFS=$IFS
IFS=','
echo "${csvInput[*]}" >> "${csvFile}"
IFS=$saveIFS
}
function json2yaml() {
# convert json files to yaml using python and PyYAML
python -c 'import sys, yaml, json; yaml.safe_dump(json.load(sys.stdin), sys.stdout, default_flow_style=False)' < "$1"
}
function yaml2json() {
# convert yaml files to json using python and PyYAML
python -c 'import sys, yaml, json; json.dump(yaml.load(sys.stdin), sys.stdout, indent=4)' < "$1"
}