#!/bin/bash
#
# Copyright (C) 2019 OX Software GmbH
# 
# This file is part of OX Automation.
#
# OX Automation is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OX Automation is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# 
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with OX Automation. If not, see <http://www.gnu.org/licenses/>.
#
#
# Authors:
# Benedikt Kroening <benedikt.kroening@open-xchange.com>
#
set -e
SCRIPT_DIR="$( cd "$(dirname "$0")" ; pwd -P)"
# sourcing some commonly used functions and executing basic checks
source ${SCRIPT_DIR}/../lib/common.bash
source ${SCRIPT_DIR}/../lib/setup.bash
DB_SERVICE_NAME=mysql

## Help text
show_usage() {
echo -n "
    --type              mysql|mariadb
    --version           5.6 ...
    --root-password
    --init

"
}

### reading config from command line; overriding defaults
POSITIONAL=()
while [[ $# -gt 0 ]]
do
key="$1"

case $key in
    -h|--help)
    show_usage
    exit 0
    shift
    ;;
    --debug)
    echo "WARNING: Debug flag set (--debug)"
    set -x
    shift
    ;;
    --type)
    DATABASE_TYPE=$s
    shift
    shift
    ;;
    --version)
    DATABASE_VERSION=$2
    shift
    shift
    ;;
    --root-password)
    DATABASE_ROOT_PASS="$2"
    shift
    shift
    ;;
    --init)
    OX_INIT=true;
    shift
    ;;
    # --foo) # non value argument
    # INSTALL_FOO=true
    # shift
    # ;;
    # --bar) # argument with value 
    # INSTALL_BAR=true
    # BAR_VAL=$2
    # shift
    # shift
    # ;;
    *) # unknown option
    echo "Unknonwn option: $1"
    POSITIONAL+=("$1") # save it in an array for later
    shift 
    ;;
esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters

if [[ -z ${DATABASE_TYPE} ]]; then
    export DATABASE_TYPE="mysql"
fi

if [[ -z ${DATABASE_VERSION} ]]; then
    export DATABASE_VERSION="5.6"
fi

checkRootPrivileges
detectDistribution

if [[ -z ${EXECUTED_preInstallActions} ]]; then
    preInstallActions
fi

echo "Database setup prepared, Following config will be used"
printenv | grep DATABASE_
echo "===   (CTRL+C to cancel)   ==="

sleep 3

if [[ "${DATABASE_TYPE}" == "mysql" ]]; then
    echo "Installing mysql-server packages..."
    echo -n "Adding MySQL repositories"

    if [[ true == "${ANY_DEB}" ]]; then
        DB_SERVICE_NAME=mysql
        # Adding mysql key
        # apt-key adv --recv-keys 5072E1F5
        gpg --keyserver keys.gnupg.net --recv-key 5072E1F5
        gpg --export -a 5072E1F5 > mysql-repo.key  
        apt-key add mysql-repo.key
        
        {
        echo "deb http://repo.mysql.com/apt/debian/ ${DIST_VERSION} mysql-$DATABASE_VERSION"
        echo "deb http://repo.mysql.com/apt/debian/ ${DIST_VERSION} mysql-tools"
        # echo "deb-src http://repo.mysql.com/apt/debian/ stretch mysql-$DATABASE_VERSION"
        } > /etc/apt/sources.list.d/mysql.list
    elif [[ true == "${ANY_SLES}" ]]; then
        echo ""
        echo "ERROR: database setup on sles not yet implemented"
        echo ""
        sleep 10
        exit 1
    elif [[ true == "${ANY_RHEL}" ]] || [[ true == "${ANY_CENTOS}" ]]; then
        DB_SERVICE_NAME=mysqld
        gpg --keyserver keys.gnupg.net --recv-key 5072E1F5
        gpg --export -a 5072E1F5 > mysql-repo.key    
        rpm --import mysql-repo.key
        
        {
        echo "[mysql-repo]"
        echo "name=MySQL ${DATABASE_VERSION} Community Server"
        echo "baseurl=http://repo.mysql.com/yum/mysql-${DATABASE_VERSION}-community/el/${DIST_VERSION}/\$basearch/"
        echo "gpgcheck=1"
        } > /etc/yum.repos.d/mysql.repo
    fi

    installPackages "mysql-server"

fi

if [[ "${OX_INIT}" == true ]]; then
    restartService ${DB_SERVICE_NAME}
    waitPort localhost 3306

    if [[ -n "${DATABASE_ROOT_PASS}" ]]; then

        if [[ true == "${ANY_RHEL}" ]] || [[ true == "${ANY_CENTOS}" ]]; then
            if [[ ${DIST_VERSION} == "7" ]]; then
                # CentOS7 / RHEL(maybe) are special and generate a temporary root password for mysql
                # We will grep it out and replace it with the provided one (if any)
                password_match=`awk '/A temporary password is generated for/ {a=$0} END{ print a }' /var/log/mysqld.log | awk '{print $(NF)}'`
                mysql -u root -p$password_match --connect-expired-password -e "SET password FOR root@localhost=password('$password_match');"
                mysql -u root -p$password_match -e "SHOW VARIABLES LIKE 'validate_password%';"
                mysql -u root -p$password_match -e "SET GLOBAL validate_password_length=4;"
                mysql -u root -p$password_match -e "SET GLOBAL validate_password_policy=LOW;"
                mysql -u root -p$password_match -e "SHOW VARIABLES LIKE 'validate_password%';"
                mysql -u root -p$password_match -e "SET password for root@localhost=password('${DATABASE_ROOT_PASS}');"
                mysql -u root -p${DATABASE_ROOT_PASS} -e "flush privileges;"
            fi
        else 
            echo "Setting MySQL root password..."
            /usr/bin/mysqladmin -u root password ${DATABASE_ROOT_PASS}
        fi


    fi
fi