Files
db-backup/scripts/dburl-parser.sh

66 lines
1.8 KiB
Bash
Executable File

#! /bin/sh
#
# Parses a database URL in the format schema://user:
#
DB_URL="$1";
DB_VAR_PREFIX="${DB_VAR_PREFIX:-DB_}";
DB_ARG_VAR_PREFIX="${DB_ARG_VAR_PREFIX:-db_arg_}";
# get URL's query args
query_args="${DB_URL#*\?}";
queryless_url="${DB_URL%%\?*}";
# get URL's schema
schema="${queryless_url%//*}";
if test "${schema}" = "${queryless_url}"; then
echo >&2 "database URLs must start with schema (i.e.: mysql://)"\
&& echo >&2 "URL_INVALID_ERROR: \"${DB_URL}\""\
&& exit 2;
fi
schemaless_url=${queryless_url#*//};
# left hand is everything until the first @ (the user part)
# with no @ there's no difference from $schemaless_url
# so $username and $password will be blank
left_hand=${schemaless_url%@*};
if test ! ${left_hand} = ${schemaless_url}; then
username=$(echo ${left_hand} | cut -d ':' -f 1);
if test ! ${username} = ${left_hand}; then
password=$(echo ${left_hand} | cut -d ':' -f 2);
fi
fi
# the right hand is the host part (after @) and will be always present
right_hand=${schemaless_url#*@};
host=$(echo ${right_hand} | cut -d ':' -f 1 | cut -d '/' -f 1);
if test -n "$(echo ${right_hand} | grep -o ':')"; then
port=$(echo ${right_hand} | cut -d ':' -f 2 | cut -d '/' -f 1);
fi
if test -n "$(echo ${right_hand} | grep -o '/')"; then
database=$(echo ${right_hand} | cut -d ':' -f 2 | cut -d '/' -f 2);
fi
# throw an error if $DB_URL is empty and so is $host
if test -z "${host}"; then
echo "database URL providen was invalid" && exit 1;
fi
cat << HEREDOC
${DB_VAR_PREFIX}SCHEMA=${schema%:}
${DB_VAR_PREFIX}USERNAME=${username}
${DB_VAR_PREFIX}PASSWORD=${password}
${DB_VAR_PREFIX}HOST=${host}
${DB_VAR_PREFIX}PORT=${port}
${DB_VAR_PREFIX}NAME=${database}
$(
echo ${query_args}\
| sed 's/[&;]/\n/g'\
| while read arg_item; do
echo "${DB_ARG_VAR_PREFIX}${arg_item}";
done
)
HEREDOC