#!/bin/bash
#  _____               _           _
# |   __|___ ___ ___ _| |___ _____| |_ ___ ___ ___
# |   __|  _| -_| -_| . | . |     | . | . |   | -_|
# |__|  |_| |___|___|___|___|_|_|_|___|___|_|_|___|
#
#                              Freedom in the Cloud
#
# mongodb database functions
#
# License
# =======
#
# Copyright (C) 2017-2018 Bob Mottram <bob@freedombone.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Set this when calling backup and restore commands
USE_MONGODB=
MONGODB_APPS_FILE=$HOME/.mongodbapps
MONGODB_PORT=27017

function store_original_mongodb_password {
    if [ ! -f /root/.mongodboriginal ]; then
        echo $'Storing original mongodb password'
        ORIGINAL_MONGODB_PASSWORD=$("${PROJECT_NAME}-pass" -u root -a mongodb)
        # We can store this in plaintext because it will soon be of historical interest only
        echo -n "$ORIGINAL_MONGODB_PASSWORD" > /root/.mongodboriginal
    fi
}

function get_mongodb_password {
    MONGODB_PASSWORD=$("${PROJECT_NAME}-pass" -u root -a mongodb)
    if [[ "$MONGODB_PASSWORD" == *'failed'* ]]; then
        echo $'Could not obtain mongodb password'
        exit 7835272
    fi
}

function install_mongodb {
    app_name=$1

    if [[ "$(uname -a)" == *"armv7"* ]]; then
        echo $'mongodb package is not available for arm 7 architecture'
        exit 7356272
    fi

    if [[ $(is_completed "${FUNCNAME[0]}") == "1" ]]; then
        return
    fi

    function_check get_mongodb_password
    get_mongodb_password
    if [ ! "$MONGODB_PASSWORD" ]; then
        if [ -f "$IMAGE_PASSWORD_FILE" ]; then
            MONGODB_PASSWORD="$(printf "%s" "$(cat "$IMAGE_PASSWORD_FILE")")"
        else
            MONGODB_PASSWORD="$(create_password "${MINIMUM_PASSWORD_LENGTH}")"
        fi
    fi
    "${PROJECT_NAME}-pass" -u root -a mongodb -p "$MONGODB_PASSWORD"

    apt-get -yq install mongodb mongo-tools
    apt-get -yq remove --purge apache2-bin*
    if [ -d /etc/apache2 ]; then
        rm -rf /etc/apache2
        echo $'Removed Apache installation after mongodb install'
    fi

    if [ ! -d /var/lib/mongodb ]; then
        echo $"ERROR: mongodb does not appear to have installed. $CHECK_MESSAGE"
        exit 78352
    fi

    if [ "$app_name" ]; then
        if ! grep -q "$app_name" "$MONGODB_APPS_FILE"; then
           echo "$app_name" >> "$MONGODB_APPS_FILE"
        fi
    fi

    mark_completed "${FUNCNAME[0]}"
}

function remove_mongodb {
    app_name=$1

    if [ ! "$app_name" ]; then
        return
    fi

    removemongo=
    if [ -f "$MONGODB_APPS_FILE" ]; then
        sed -i "/$app_name/d" "$MONGODB_APPS_FILE"
        if [ ! -s "$MONGODB_APPS_FILE" ]; then
            removemongo=1
        fi
    else
        removemongo=1
    fi

    if [ $removemongo ]; then
        systemctl stop mongodb
        systemctl disable mongodb
        apt-get -yq remove --purge mongodb mongo-tools
        apt-get -yq autoremove
        if [ -d /var/lib/mongodb ]; then
            rm -rf /var/lib/mongodb
        fi
        if [ -f /etc/systemd/system/mongodb.service ]; then
            rm /etc/systemd/system/mongodb.service
            systemctl daemon-reload
        fi
        if [ -f /etc/init.d/mongodb ]; then
            rm /etc/init.d/mongodb
        fi
        sed -i '/install_mongodb/d' "$COMPLETION_FILE"
    fi
}

function add_mongodb_user {
    mongodb_username=$1
    mongodb_password=$2

    mongo admin --eval "db.createUser({user: '$mongodb_username', pwd: '$mongodb_password', roles: [ { role: 'userAdminAnyDatabase', db: 'admin' } ] })"
}

function remove_mongodb_user {
    mongodb_username=$1
    mongo admin --eval "db.removeUser($mongodb_username)"
}

function drop_database_mongodb {
    database_name="$1"
    if [[ "$database_name" == 'admin' ]]; then
        return
    fi
    mongo "$database_name" --eval "db.runCommand( { dropDatabase: 1 } )"
    if [ "$app_name" ]; then
        if grep -q "$app_name" "$MONGODB_APPS_FILE"; then
            sed -i "/$app_name/d" "$MONGODB_APPS_FILE"
        fi
    fi
}

function initialise_database_mongodb {
    database_name=$1
    database_file=$2
    if ! mongorestore "$database_file"; then
        exit 8358365
    fi
}

function create_database_mongodb {
    app_name="$1"
    app_admin_password="$2"
    app_admin_username="$3"
    mongo admin --eval "db.createUser({user: '$app_admin_username', pwd: '$app_admin_password', roles: [ { role: 'userAdminAnyDatabase', db: 'admin' } ] })"
    if [ "$app_name" ]; then
        if ! grep -q "$app_name" "$MONGODB_APPS_FILE"; then
           echo "$app_name" >> "$MONGODB_APPS_FILE"
        fi
    fi
}

# NOTE: deliberately there is no "exit 0"