#!/bin/sh

DIR_CFG=/etc/bareos
CFG_DIR=${DIR_CFG}/bareos-dir.conf
DIR_SCRIPTS=/usr/lib/bareos/scripts

SEC_GROUPS="tape disk"

WORKING_DIR="/var/lib/bareos"
FILE_DAEMON_USER="root"
FILE_DAEMON_GROUP="bareos"
STORAGE_DAEMON_USER="bareos"
STORAGE_DAEMON_GROUP="bareos"
DIRECTOR_DAEMON_USER="bareos"
DIRECTOR_DAEMON_GROUP="bareos"

PASSWORD_SUBST="\
XXX_REPLACE_WITH_DIRECTOR_PASSWORD_XXX \
XXX_REPLACE_WITH_CLIENT_PASSWORD_XXX \
XXX_REPLACE_WITH_STORAGE_PASSWORD_XXX \
XXX_REPLACE_WITH_DIRECTOR_MONITOR_PASSWORD_XXX \
XXX_REPLACE_WITH_CLIENT_MONITOR_PASSWORD_XXX \
XXX_REPLACE_WITH_STORAGE_MONITOR_PASSWORD_XXX \
"

os_type=`uname -s`

usage()
{
cat <<-EOT
usage: $0 <function>
EOT
    exit 1
}

help()
{
    usage
}

is_function()
{
    func=$1
    test "$func" && type "$func" > /dev/null 2>&1
    return $?
}

# does not work on all shells (only bash), 
# therefore removed until a better solution is found
# list_functions()
# {
#     if type typeset >/dev/null 2>&1; then
#         # show available shell functions,
#         # but exclude internal functions (name starts with "_" ...)
#         typeset -F | cut -d " " -f 3 | grep "^[a-z]"
#     else
#         echo "function list not available"
#     fi
# }

get_user_fd()
{
    echo "${FILE_DAEMON_USER}"
}

get_group_fd()
{
    echo "${FILE_DAEMON_GROUP}"
}

get_user_sd()
{
    echo "${STORAGE_DAEMON_USER}"
}

get_group_sd()
{
    echo "${STORAGE_DAEMON_GROUP}"
}

get_user_dir()
{
    echo "${DIRECTOR_DAEMON_USER}"
}

get_group_dir()
{
    echo "${DIRECTOR_DAEMON_GROUP}"
}

[ ${os_type} = Linux ] && \
setup_sd_user()
{
    #
    # guaranties that storage-daemon user and group exists
    # and storage-daemon user belongs to the required groups.
    #
    # normally, storage-daemon user
    # is already installed by the package preinstall script.
    #

    #
    # See what secondary groups exist for the sd user to be added to.
    #
    ADD_GROUPS=""
    for sec_group in ${SEC_GROUPS}; do
        cnt=`getent group ${sec_group} | wc -l`
        if [ ${cnt} -gt 0 ]; then
            [ -z "${ADD_GROUPS}" ] && ADD_GROUPS="-G ${sec_group}" || ADD_GROUPS="${ADD_GROUPS},${sec_group}"
        fi
    done

    getent group ${STORAGE_DAEMON_GROUP} > /dev/null || groupadd -r ${STORAGE_DAEMON_GROUP}

    #
    # If the user doesn't exist create a new one otherwise modify it to have the wanted secondary groups.
    #
    if [ "${STORAGE_DAEMON_USER}" != "root" ]; then
        getent passwd ${STORAGE_DAEMON_USER} > /dev/null
        if [ $? -ne 0 ]; then
            # create a new storage_daemon_user
            useradd -r --comment "bareos" --home ${WORKING_DIR} -g ${STORAGE_DAEMON_GROUP} ${ADD_GROUPS} --shell /bin/false ${STORAGE_DAEMON_USER}
        fi

        # if the user has already created before,
        # make sure the correct primary group is set otherwise fix it.
        if [ "`id -gn ${STORAGE_DAEMON_USER}`" != "${STORAGE_DAEMON_GROUP}" ]; then
            usermod -g ${STORAGE_DAEMON_GROUP} ${STORAGE_DAEMON_USER}
        fi

        # add the storage_daemon_user to additional groups (if defined)
        [ "${ADD_GROUPS}" ] && usermod ${ADD_GROUPS} ${STORAGE_DAEMON_USER}
    fi
}

[ ${os_type} != Linux ] && \
setup_sd_user()
{
   echo "setup_sd_user() is not supported on this platform"
   exit 1
}

get_database_driver()
{
    if ! [ -r "${CFG_DIR}" ]; then
        return
    fi

    # get dbdriver, that is defined in director configuration.
    # If string is still set to default, return nothing
    DBDRIVER=`sed -r -n 's/^\s*dbdriver\s*=\s*["]?([^"]*)["]?/\1/ip' "${CFG_DIR}" | grep -v "XXX_REPLACE_WITH_DATABASE_DRIVER_XXX"`

    echo "$DBDRIVER"
}

get_databases_installed()
{
    #for i in `ls ${DIR_SCRIPTS}/create_*_database`
    #do
    #    sed -n -r 's#.*/create_([a-z]+)_database#\1#p' <<<$i | grep -v bareos
    #done

    # manually check different backends, to get the correct order
    [ -e ${DIR_SCRIPTS}/create_postgresql_database ] && echo "postgresql"
    [ -e ${DIR_SCRIPTS}/create_mysql_database ] && echo "mysql"
    [ -e ${DIR_SCRIPTS}/create_sqlite3_database ] && echo "sqlite3"
}

get_database_driver_default()
{
    DBDRIVER=`get_database_driver`

    if [ -z "$DBDRIVER" ]; then
        DBDRIVER=`get_databases_installed | head -n 1`
    fi

    if [ -z "$DBDRIVER" ]; then
        # fallback and first choice
        DBDRIVER="postgresql"
    fi

    echo "$DBDRIVER"
}

initialize_database_driver()
{
    DBDRIVER=`get_database_driver_default`
    replace "XXX_REPLACE_WITH_DATABASE_DRIVER_XXX" "${DBDRIVER}"
}

get_local_hostname()
{
    # put actual short hostname in configuration files
    # try to get short hostname
    hname=`hostname -s`
    if [ -z "$hname" ]; then
        # try to get long hostname
        hname=`hostname|sed 's/\..*//g'`
        if [ -z "$hname" ]; then
            # set to "localhost"
            hname='localhost'
        fi
    fi
    echo "$hname"
}

replace()
{
    if ! [ $# -eq 2 ]; then
        return 1
    fi

    SEARCH="$1"
    REPLACE="$2"

    for file in `grep -l ${SEARCH} ${DIR_CFG}/*.conf`
    do
        echo "replacing '${SEARCH}' with '${REPLACE}' in $file"
        sed -i'' "s#${SEARCH}#${REPLACE}#g" ${file};
    done
    return 0
}

initialize_local_hostname()
{
    #
    # Replace all XXX_REPLACE_WITH_LOCAL_HOSTNAME by the local hostname.
    #
    hname=`get_local_hostname`
    replace "XXX_REPLACE_WITH_LOCAL_HOSTNAME_XXX-dir" "${hname}-dir"
    replace "XXX_REPLACE_WITH_LOCAL_HOSTNAME_XXX-fd" "${hname}-fd"
    replace "XXX_REPLACE_WITH_LOCAL_HOSTNAME_XXX-sd" "${hname}-sd"
    replace "XXX_REPLACE_WITH_LOCAL_HOSTNAME_XXX-mon" "${hname}-mon"
    replace "XXX_REPLACE_WITH_LOCAL_HOSTNAME_XXX" "${hname}"
}

replace_password()
{
    if ! [ $# -eq 2 ]; then
        return 1
    fi

    SEARCH="$1"
    REPLACE="$2"

    for file in `grep -l ${SEARCH} ${DIR_CFG}/*.conf`
    do
        echo "replacing '${SEARCH}' in $file"
        sed -i'' "s#${SEARCH}#${REPLACE}#g" ${file};
    done
    return 0
}

initialize_passwords()
{
    #
    # See if we need to generate a set of random passwords.
    #
    if [ ! -f ${DIR_CFG}/.rndpwd ]; then
        for string in ${PASSWORD_SUBST}
        do
           pass=`openssl rand -base64 33`
           echo "${string}=${pass}" >> ${DIR_CFG}/.rndpwd
        done
        chmod 400 ${DIR_CFG}/.rndpwd
    fi

    # Source the passwords
    . ${DIR_CFG}/.rndpwd

    for string in ${PASSWORD_SUBST}
    do
        eval "pass=\${$string}"
        if [ ! -z "${pass}" ]; then
            replace_password "${string}" "${pass}"
        fi
    done
}

init()
{
    initialize_local_hostname
    #initialize_director_hostname
    initialize_passwords
    initialize_database_driver
}

# number of args passed
args=$#

# without parameter, nothing is done.
# this allows this script to be sourced
# to use its functions
if [ $args -ge 1 ]; then
    # executes given arguments
    if is_function $1; then
        $*
    else
        echo "failed to execute $*. Not found."
        #usage
        exit 127
    fi
fi
