Skip to content

Instantly share code, notes, and snippets.

@dpshelio
Created July 5, 2021 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpshelio/9d5842a02ee7bb2b7bda1dcffc75678e to your computer and use it in GitHub Desktop.
Save dpshelio/9d5842a02ee7bb2b7bda1dcffc75678e to your computer and use it in GitHub Desktop.
bash script to setup gitconfig
#!/bin/env bash
# Script to clean and recover git configs before teaching.
# Based on script example from
# https://dbwebb.se/kunskap/create-bash-script-with-options-commands-and-arguments
SCRIPT=$( basename "$0" )
VERSION="0.1"
BACKUP_PATTERN=".${USER}_gitconfig"
HOURS=6
function usage
{
local txt=(
"Utility ${SCRIPT} for preparing and recovering the setup for a Carpentries git workshop."
"Usage: $SCRIPT [options] <command> [arguments]"
""
"Command:"
" clean Back-up current configuration and creates empty .gitconfig."
" recover [remove] Loads the latest back-up back in place ('remove' removes the backup)."
""
"Options:"
" --help, -h Print help."
" --version, -v Print version."
)
printf "%s\n" "${txt[@]}"
}
function badUsage
{
local message="$1"
local txt=(
"For an overview of the command, execute:"
"$SCRIPT --help"
)
[[ $message ]] && echo "$message"
printf "%s\n" "${txt[@]}"
}
function version
{
local txt=(
"$SCRIPT version $VERSION"
)
printf "%s\n" "${txt[@]}"
}
function app-clean
{
local now
now=$(date +"%Y%m%d_%H%M")
mv ~/.gitconfig ~/"${BACKUP_PATTERN}_${now}"
git config --global user.name "Vlad Dracula"
git config --global user.email "vlad@tran.sylvan.ia"
}
function find_latest
{
local pattern="$1"
local files_match
mapfile -t files_match < <(find ~/ -maxdepth 1 -type f -iname "*${pattern}_*" | sort -r)
echo "${files_match[@]}"
}
function dates_difference
{
local file_dates
local dates
local now_s
file_dates=$( echo "$1" | sed 's/.*\([0-9]\{8\}_[0-9]\{4\}\)/\1/' | sed 's/_/ /')
dates=$(date -d "${file_dates}" "+%s")
now_s=$(date +"%s")
echo $(( (now_s - dates) / 3600 ))
}
function app-recover
{
local remove="$1"
local force="${2:-FALSE}"
local list_files
list_files=$(find_latest "${BACKUP_PATTERN}")
diff_now=$(dates_difference "${list_files[0]}")
if (( diff_now > HOURS )); then
if [ "$force" != "-f" ]; then
echo "WARNING: The Backup is older than ${HOURS} hours (${diff_now}). Use '-f' to force its recovery"
echo " Run, cat ${list_files[0]} to see its content"
exit 1
else
echo "WARNING: Overwriting file with a file older than ${HOURS} hours (${diff_now})."
fi
fi
if [ "$remove" == "remove" ]; then
action="mv"
else
action="cp"
fi
${action} "${list_files[0]}" ~/.gitconfig
}
while (( $# ))
do
case "$1" in
--help | -h)
usage
exit 0
;;
--version | -v)
version
exit 0
;;
clean \
| recover)
command="$1"
shift
app-"$command" "$@"
exit 0
;;
*)
badUsage "Option/command not recognised."
exit 1
;;
esac
done
badUsage
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment