Current File : //home/keyhelp/www/keyhelp/bin/disaster_recovery.sh
#!/bin/bash

#
#  _  __          _   _     _      (R)
# | |/ /___ _   _| |_| |___| |___
# | | /  -_) |_/ |  _  | -_) | _ \
# |_|\_\___|\__, |_| |_|___|_|  _/
#           |___/            |_|
#
# @author  Alexander Mahr <am@keyweb.de>
# @link    https://www.keyhelp.de
#

# - GLOBALS -----------------

    DB_ROOT_USER='root'
    DB_PASSWORD=''

    SCRIPT_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# - FUNCTIONS ---------------

    #
    # Try to find your login credentials for a privileged database user.
    #
    function tryLogin()
    {
        if [ `checkDbConnection` = 0 ]; then
            return 0
        fi

        DB_CONFIG_FILE='/etc/mysql/debian.cnf'
        if [[ -f "$DB_CONFIG_FILE" && -r "$DB_CONFIG_FILE" ]]; then

            DB_ROOT_USER='debian-sys-maint'
            DB_PASSWORD=$(awk '/^password/ {print $3; exit}' "$DB_CONFIG_FILE")

            if [ `checkDbConnection` = 0 ]; then
                return 0
            fi
        fi

        # Set variables to default values
        DB_ROOT_USER='root'
        DB_PASSWORD=''
        return 1
    }


    #
    # Check if login is possible with current login credentials.
    #
    # return    int    Returns 0 on success, returns >0 on failure
    function checkDbConnection()
    {
        mysql --user="$DB_ROOT_USER" --password="$DB_PASSWORD"  -e ";" > /dev/null 2>&1
        echo $?
    }


    #
    # Import a database
    #
    # 1st param    string    The database name.
    # 2nd param    string    The import .sql file.
    function importDatabase()
    {
        mysql --user="$DB_ROOT_USER" --password="$DB_PASSWORD" -e "CREATE DATABASE IF NOT EXISTS \`$1\`;"
        if [ $? -gt 0 ]; then
            return 1
        fi

        mysql --user="$DB_ROOT_USER" --password="$DB_PASSWORD" "$1" < "$2"
    }

    #
    # Return the current os name and version
    #
    # return    string    Format eg "Ubuntu_24.04", "Debian_13", ...
    function getOs()
    {
        local distro
        local version

        if [ `uname -s` = 'Linux' ] && [ -e '/etc/debian_version' ]; then
            if [ -e '/etc/lsb-release' ]; then
                # mostly ubuntu, but also debian can have it too
                . /etc/lsb-release
                distro="$DISTRIB_ID"
                version="$DISTRIB_RELEASE"
            else
                distro="Debian"
                version=`head -n 1 /etc/debian_version`
            fi

            if [ $distro = "Debian" ]; then
                version=`echo $version | grep -o "^[0-9]\+"`
            fi
        else
            echo 'false'
        fi

        echo ${distro}_$version
    }


    #
    # Echo colored 'failure' string
    #
    function echoFailure()
    {
        echo -e "\033[1;31m[FAILURE]\033[0m "
    }

    #
    # Echo colored 'okay' string
    #
    function echoOkay()
    {
        echo -e "\033[1;32m[OKAY]\033[0m "
    }

# ---------------------------
# - PROGRAM FLOW ------------
# ---------------------------

    echo
    echo '-----------------------------------------'
    echo ' KeyHelp Database Disaster Recovery v0.1'
    echo '-----------------------------------------'
    echo
    echo 'This script allows you to import all '
    echo 'databases in this backup at once.'


    # connect DB

        echo
        printf 'Check database connection ... '

        tryLogin

        if [ $? = 0 ]; then
            echoOkay
        else
            echoFailure

            while [ `checkDbConnection` != 0 ]; do
                echo
                echo "Can't connect to database!"
                read -p "Please enter password for root user: " DB_PASSWORD
            done
        fi


    # get all sql files

        echo
        printf 'Looking for files to import ... '

        SQL_FILES=()
        while IFS= read -r -d $'\0'; do
            SQL_FILES+=("$REPLY")
        done < <(find $SCRIPT_PATH -maxdepth 2 -name "*.sql" -not -name "information_schema.sql" -not -name "performance_schema.sql" -print0)

        if [ -z "$SQL_FILES" ]; then
            echoFailure

            echo
            echo 'No SQL files found!'
            echo 'Please make sure that this script is'
            echo 'located inside the "/database/" folder'
            echo 'of your KeyHelp backup archive.'
            echo
            exit 1
        else
            echoOkay
        fi


    # show all sql files to user, ask if we should go on

        echo
        for SQL_FILE in "${SQL_FILES[@]}"; do
            echo  "   '$SQL_FILE'"
        done

        LOOP=1
        while [ $LOOP = 1 ]; do
            echo
            read -p 'Start importing [yes,no]? ' INPUT

            case $INPUT in
              y|Y|'yes')
               LOOP=0
                ;;
              n|N|'no')
                echo 'bye'
                exit
                ;;
              *)
                LOOP=1
                ;;
            esac
        done


    # import

        echo
        echo 'Importing'
        echo

        for SQL_FILE in "${SQL_FILES[@]}"; do
            printf "   '$SQL_FILE' ... "

            DATABASE=$(basename "$SQL_FILE" '.sql')
            importDatabase "$DATABASE" "$SQL_FILE"

            if [ $? = 0 ]; then
                echoOkay
            else
                echoFailure
            fi
        done

    # finished

        echo
        echo 'Finished!'
        echo 'bye'