#!/bin/bash
#
#
#   OPEN-XCHANGE legal information
#
#   All intellectual property rights in the Software are protected by
#   international copyright laws.
#
#
#   In some countries OX, OX Open-Xchange, open xchange and OXtender
#   as well as the corresponding Logos OX Open-Xchange and OX are registered
#   trademarks of the OX Software GmbH group of companies.
#   The use of the Logos is not covered by the GNU General Public License.
#   Instead, you are allowed to use these Logos according to the terms and
#   conditions of the Creative Commons License, Version 2.5, Attribution,
#   Non-commercial, ShareAlike, and the interpretation of the term
#   Non-commercial applicable to the aforementioned license is published
#   on the web site http://www.open-xchange.com/EN/legal/index.html.
#
#   Please make sure that third-party modules and libraries are used
#   according to their respective licenses.
#
#   Any modifications to this package must retain all copyright notices
#   of the original copyright holder(s) for the original code used.
#   After any such modifications, the original and derivative code shall remain
#   under the copyright of the copyright holder(s) and/or original author(s)per
#   the Attribution and Assignment Agreement that can be located at
#   http://www.open-xchange.com/EN/developer/. The contributing author shall be
#   given Attribution for the derivative code and a license granting use.
#
#    Copyright (C) 2016-2020 OX Software GmbH
#    Mail: info@open-xchange.com
#
#
#    This program is free software; you can redistribute it and/or modify it
#    under the terms of the GNU General Public License, Version 2 as published
#    by the Free Software Foundation.
#
#    This program 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 this program; if not, write to the Free Software Foundation, Inc., 59
#    Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#

# some defaults
DCS_PROPERTIES="/opt/open-xchange/etc/documents-collaboration-client.properties"

DCSDB_SEARCHKEY_HOST=
DCSDB_SEARCHKEY_PORT=
DCSDB_SEARCHKEY_SCHEMA=
DCSDB_SEARCHKEY_USERNAME=com.openexchange.dcs.client.database.userName
DCSDB_SEARCHKEY_PASSWORD=com.openexchange.dcs.client.database.password
DCSDB_SEARCHKEY_CONNECTION_URL=com.openexchange.dcs.client.database.connectionURL

# Options
DCS_PROPERTIES_LONG=properties
DCS_PROPERTIES_SHORT=p

# Actions
DCS_ACTION_LIST='false'
DCS_ACTION_CLEAR='false'
DCS_ACTION_YES='false'

LONGOPTS='$DCS_PROPERTIES_LONG:'
NEEDED_EXECUTABLES="mysql sed"

die() {
    test -n "$1" && echo 1>&2 "$1" || echo 1>&2 "ERROR"
    exit 1
}

continue_question() {
    if [[ -t 0 ]]; then
        local ANSWER

        read -r -p "$1 [y/N] " ANSWER

        if [[ ! ${ANSWER} =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
}

# help/usage text
usage() {
    local LOPTS=$(echo ${LONGOPTS} | sed -e 's/[:,]/ /g')

    echo
    echo "$0 currently knows the following parameters:"
    echo

    printf '%-30s | %s\n' "Parameter" "Default value"
    echo "------------------------------------------------------------"

    for CUROPT in $LOPTS; do
        local RVAR=${CUROPT%_LONG}
        local DEFAULT=$(eval echo ${RVAR})
        local SHORTOPT=$(eval echo "${RVAR}_SHORT")
        local LONGOPT=$(eval echo ${CUROPT})
        printf '%-30s | %s\n' "-${SHORTOPT} | --${LONGOPT}" ${DEFAULT}
    done
    echo
    echo
    echo 'NOTE: use "-l" to list all documents-collaboration servers, currently registered.'
    echo 'NOTE: use "-c" to remove all documents-collaboration servers, currently registered.'
    echo 'NOTE: use "-y" to automatically answer questions with y(es).'
    echo 'NOTE: use "-h" to show this help text.'
    echo
    echo
cat<<EOF
Example:

  $0 -l
EOF
    echo
    exit 0
}

# read and validate properties function
read_properties() {
    if [[ -n ${DCS_PROPERTIES} ]] && [[ -f ${DCS_PROPERTIES} ]]; then
        local REGEX_PREFFIX='^[[:space:]]*'
        local REGEX_POSTFIX='[[:space:]]*=[[:space:]]*(.+)[[:space:]]*$'

        while read CUR_LINE; do
            if [[ $CUR_LINE =~ ${REGEX_PREFFIX}${DCSDB_SEARCHKEY_HOST}${REGEX_POSTFIX} ]]; then
                DCSDB_HOST=${BASH_REMATCH[1]}
            elif [[ $CUR_LINE =~ ${REGEX_PREFFIX}${DCSDB_SEARCHKEY_PORT}${REGEX_POSTFIX} ]]; then
                DCSDB_PORT=${BASH_REMATCH[1]}
            elif [[ $CUR_LINE =~ ${REGEX_PREFFIX}${DCSDB_SEARCHKEY_SCHEMA}${REGEX_POSTFIX} ]]; then
                DCSDB_SCHEMA=${BASH_REMATCH[1]}
            elif [[ $CUR_LINE =~ ${REGEX_PREFFIX}${DCSDB_SEARCHKEY_USERNAME}${REGEX_POSTFIX} ]]; then
                DCSDB_USERNAME=${BASH_REMATCH[1]}
            elif [[ $CUR_LINE =~ ${REGEX_PREFFIX}${DCSDB_SEARCHKEY_PASSWORD}${REGEX_POSTFIX} ]]; then
                DCSDB_PASSWORD=${BASH_REMATCH[1]}
            elif [[ $CUR_LINE =~ ${REGEX_PREFFIX}${DCSDB_SEARCHKEY_CONNECTION_URL}${REGEX_POSTFIX} ]]; then
                DCSDB_URL=${BASH_REMATCH[1]}

                if [[ $DCSDB_URL =~ jdbc:mysql://([^:^/]+)[:]?([0-9]*)/(.*) ]]; then
                    DCSDB_HOST=${BASH_REMATCH[1]}
                    DCSDB_PORT=${BASH_REMATCH[2]}
                    DCSDB_SCHEMA=${BASH_REMATCH[3]}
                fi
            fi
        done < "${DCS_PROPERTIES}"

        if [[ -z $DCSDB_HOST ]]; then
            DCSDB_HOST=localhost
        fi

        if [[ -z $DCSDB_PORT ]]; then
            DCSDB_PORT=3306
        fi

        if [[ -z $DCSDB_SCHEMA ]]; then
            DCSDB_SCHEMA=dcsdb
        fi
    else
        echo "Invalid properties file given: ${DCS_PROPERTIES}"
        exit 3
    fi
}

# inappropriate parameters
if [ $# -le 0 ]; then
    usage
    exit 1
fi

# check prerequisites
for CUR_EXECUTABLE in ${NEEDED_EXECUTABLES}; do
    if ! hash ${CUR_EXECUTABLE} 2>/dev/null; then
        echo "Needed binary cannot be found: ${CUR_EXECUTABLE}. Aborting!"
        exit 2
    fi
done

# read and evaluate command line params
TEMP=$(POSIXLY_CORRECT=true getopt -o p:hlcy --long "$(eval echo ${LONGOPTS}),help" -- "$@")
eval set -- "$TEMP"

while true; do
    case "$1" in
    -p|--${DCS_PROPERTIES_LONG})
        DCS_PROPERTIES=${2}
        shift 2
        ;;
    -l)
        DCS_ACTION_LIST='true'
        shift
        ;;
    -c)
        DCS_ACTION_CLEAR='true'
        shift
        ;;
    -y)
        DCS_ACTION_YES='true'
        shift
        ;;
    -h|--help)
        usage
        exit 1
        shift
        ;;
    --)
        shift
        break
        ;;
    *)
        die "Internal error!"
        exit 1
        ;;
    esac
done

# read properties
read_properties

# list action
if [ 'true' = ${DCS_ACTION_LIST} ]; then
    mysql -u ${DCSDB_USERNAME} -h ${DCSDB_HOST} -P ${DCSDB_PORT} -p${DCSDB_PASSWORD} -e "SELECT * FROM \`${DCSDB_SCHEMA}\`.DCS"

    LIST_ERROR=$?

    if [[ ${LIST_ERROR} -ne 0 ]]; then
        exit ${LIST_ERROR}
    fi
fi

# clear action
if [ 'true' = ${DCS_ACTION_CLEAR} ]; then
    echo

    if [ 'true' = ${DCS_ACTION_YES} ] || continue_question "This operation will remove all currently registered documents-collaboration servers from the database. Do you really want to continue"; then
        mysql -u ${DCSDB_USERNAME} -h ${DCSDB_HOST} -P ${DCSDB_PORT} -p${DCSDB_PASSWORD} -e "DELETE FROM \`${DCSDB_SCHEMA}\`.DCS"

        LIST_ERROR=$?

        if [[ ${LIST_ERROR} -ne 0 ]]; then
            exit ${LIST_ERROR}
        fi

        echo "All registered documents-collaboration servers removed from database. Please (re)start all documents-collaboration servers if needed."
    fi
fi

# all good
exit 0
