salix/db/import-changes.sh

114 lines
2.6 KiB
Bash
Executable File

#!/bin/bash
FORCE=FALSE
usage() {
echo "[ERROR] Usage: $0 [-f] [environment]"
exit 1
}
while getopts ":f" option
do
case $option in
f)
FORCE=TRUE
;;
\?|:)
usage
;;
esac
done
shift $(($OPTIND - 1))
ENV=$1
DIR="$(dirname "${BASH_SOURCE[0]}")"
# Production protection
if [ "$ENV" == "production" ]; then
echo ""
echo " ( ( ) ( ( ) ) "
echo " )\ ))\ ) ( /( )\ ) ( ))\ ) ( /( ( /( "
echo "(()/(()/( )\()|()/( ( )\ ) /(()/( )\()) )\())"
echo " /(_))(_)|(_)\ /(_)) )\ (((_) ( )(_))(_)|(_)\ ((_)\ "
echo "(_))(_)) ((_|_))_ _ ((_))\___(_(_()|_)) ((_) _((_)"
echo "| _ \ _ \ / _ \| \| | | ((/ __|_ _|_ _| / _ \| \| |"
echo "| _/ /| (_) | |) | |_| || (__ | | | | | (_) | . |"
echo "|_| |_|_\ \___/|___/ \___/ \___| |_| |___| \___/|_|\_|"
echo ""
if [ "$FORCE" != "TRUE" ]; then
read -p "[INTERACTIVE] Are you sure? (Default: no) [yes|no]: " ANSWER
if [ "$ANSWER" != "yes" ]; then
echo "[INFO] Aborting changes."
exit
fi
fi
fi
# Configuration file
if [ -z "$ENV" ]; then
INI_FILE="$DIR/config.ini"
else
INI_FILE="$DIR/config.$ENV.ini"
fi
if [ ! -f "$INI_FILE" ]; then
echo "[ERROR] Config file doesn't exists: $INI_FILE"
exit 2
fi
echo "[INFO] Using config file: $INI_FILE"
# Fetching database version
GET_VERSION="SELECT dbVersion FROM util.config LIMIT 1"
DB_VERSION=`echo "$GET_VERSION" | mysql --defaults-file="$INI_FILE" --silent --raw`
echo "[INFO] Current database version: $DB_VERSION"
if [[ ! "$DB_VERSION" =~ ^[0-9]+$ ]]; then
echo "[ERROR] Cannot fetch the database version."
exit 3
fi
# Applying changes
N_CHANGES=0
echo "[INFO] Applying changes."
for DIR_PATH in "$DIR/changes/"*; do
DIR_NAME=$(basename $DIR_PATH)
DIR_VERSION=${DIR_NAME:0:5}
if [[ ! "$DIR_NAME" =~ ^[0-9]{5}(-[a-zA-Z0-9]+)?$ ]]; then
echo "[WARN] Ignoring wrong directory name: $DIR_NAME"
continue
fi
if [ "$DB_VERSION" -ge "$DIR_VERSION" ]; then
echo "[INFO] Ignoring already applied version: $DIR_NAME"
continue
fi
echo "[INFO] Applying version: $DIR_NAME"
for FILE in "$DIR_PATH/"*; do
echo "[INFO] -> $(basename "$FILE")"
mysql --defaults-file="$INI_FILE" --comments < $FILE
N_CHANGES=$((N_CHANGES + 1))
done
UPDATE_VERSION="UPDATE util.config SET dbVersion='$DIR_VERSION'"
echo "$UPDATE_VERSION" | mysql --defaults-file="$INI_FILE"
done
if [ "$N_CHANGES" -eq "0" ]; then
echo "[INFO] No changes to apply."
else
echo "[INFO] Changes applied succesfully."
fi