
#!/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:
# Daniel Pondruff <daniel.pondruffopen-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
source ${SCRIPT_DIR}/../lib/dovecot.bash
checkRootPrivileges
detectDistribution

## Help text
show_usage() {
echo -n "
  $0 [OPTIONS]
  
    --install
    --enable
    --disable
    --restart
    -k | --key <value>

"
}


### 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
    ;;
    --enable)
    FEATURE_ENABLE=true
    shift
    ;;
    --disable)
    FEATURE_ENABLE=false
    shift
    ;;
    --install)
    FEATURE_INSTALL=true
    shift
    ;;
    -k|--key)
    value="$2"
    shift
    shift
    ;;
    --restart)
    RESTART_OX=true
    shift
    ;;
    *)    # unknown option
    POSITIONAL+=("$1") # save it in an array for later
    shift 
    ;;
esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters

if [[ "${FEATURE_INSTALL}" = true  ]]; then
    if [[ true == "${ANY_DEB}" ]]; then
        # Adding dovecot key
        apt-key adv --fetch-keys https://repo.dovecot.org/DOVECOT-REPO-GPG
        {
        echo "deb http://repo.mysql.com/apt/debian/ ${DIST_VERSION} mysql-$DATABASE_VERSION"
        } > /etc/apt/sources.list.d/dovecot.list

    elif [[ true == "${ANY_SLES}" ]]; then
        echo ""
        echo "ERROR: dovecot setup on sles not yet implemented"
        echo ""
        sleep 10
        exit 1
    elif [[ true == "${ANY_RHEL}" ]] || [[ true == "${ANY_CENTOS}" ]]; then
        echo ""
        echo "ERROR: dovecot setup on rhel/centos not yet implemented"
        echo ""
        sleep 10
        exit 1 
    fi
    installPackages "dovecot-core dovecot-imapd dovecot-lmtpd dovecot-managesieved dovecot-sieve dovecot-pop3d dovecot-ldap postfix rsyslog"
    echo "Copy Dovecot Configs"
    rm -rf /etc/dovecot/*
    cp -R config/dovecot/etc/dovecot/* /etc/dovecot/
    restartService dovecot

INIT_STATE_FILE="/etc/dovecot/dovecot-init-done"

if [ ! -f "/etc/dovecot/dovecot.conf" ]; then
  # Copy default config
  echo "Copying default config from /etc/dovecot.dist"
  cp -R /etc/dovecot.dist/* /etc/dovecot/
fi


if [ ! -f ${INIT_STATE_FILE} ]; then
    echo "Executing init-config script (dovecot-backend) "
    echo "$0 $@"
    echo "Creating user and group: vmail"
    groupadd -g 5000 vmail
    useradd -u 5000 -g 5000 -m -d /home/vmail -s /bin/false vmail
    adduser dovecot vmail
    # Create log dir and adjust permissions
    mkdir -p /var/log/dovecot
    touch /var/log/dovecot/debug.log
    touch /var/log/dovecot/info.log
    touch /var/log/dovecot/error.log
    chown -R vmail:dovecot /var/log/dovecot*
    echo "Creating directory for dovecot acl informations"
    mkdir -p /var/lib/dovecot/db
    chmod 0770 /var/lib/dovecot
    echo "Creating dictionary for shared namespace"
    touch /var/lib/dovecot/db/shared-mailboxes.db
    echo "Creating virtual directories"
    mkdir -p /var/lib/dovecot/virtual/all
    chmod -R 700 /var/lib/dovecot/virtual
    echo "*
    -INBOX/Trash
    -INBOX/Trash/*
    -INBOX/Spam
    -INBOX/Spam/*
      all" > /var/lib/dovecot/virtual/all/dovecot-virtual
    chown -R vmail:vmail /var/lib/dovecot
    LDA_PATH="/usr/lib/dovecot/dovecot-lda"
    echo "dovecot     unix     -     n     n     -     -     pipe" >> /etc/postfix/master.cf
    echo "  flags=DRhu user=vmail:vmail argv=${LDA_PATH} -f \${sender} -d \${user}" >> /etc/postfix/master.cf
    echo "$(date)" > ${INIT_STATE_FILE}


    echo "Configure postfix main.cf"
    postconf -e "myhostname = dovecot"
    postconf -e "smtpd_use_tls = no"
    postconf -e "myorigin = \$mydomain"
    postconf -e "mydestination = "
    postconf -e "relayhost = "\$mydomain
    #postconf -e "smtpd_tls_cert_file=${SSL_DIR}/certs/${FQDN}.crt"
    #postconf -e "smtpd_tls_key_file=${SSL_DIR}/private/${FQDN}.key"
    postconf -e "dovecot_destination_recipient_limit = 1"
    postconf -e "virtual_mailbox_domains = ${MAIL_DOMAIN}"
    postconf -e "virtual_transport = dovecot"
    postconf -e "myorigin = \$mydomain"
    postconf -e "mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 ${ENV_SUBNET}"
    # set home permissions every time ...
    chown -R vmail:vmail /home/vmail
    chmod 2770 /home/vmail
fi
elif [[ "${FEATURE_ENABLE}" = true  ]]; then
  INPUT=${SCRIPT_DIR}/../config/environment/qa/users.csv
  OLDIFS=$IFS
  IFS=','
  [ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
  while read username password
  do
    if [[ "$username" == "#"* ]]; then 
          # skipping commented out line 
          continue
    fi
  	#echo "username : $username"
    /opt/open-xchange/sbin/changeuser -u $username -c 10 -A oxadmin -P secret --imapserver "dovecot.qa.open-xchange.com" --smtpserver "dovecot.qa.open-xchange.com"
  	# echo "password : $password"
  done < $INPUT
  IFS=$OLDIFS
elif [[ "${FEATURE_ENABLE}" = false  ]]; then
  INPUT=${SCRIPT_DIR}/../config/environment/qa/users.csv
  OLDIFS=$IFS
  IFS=','
  [ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
  while read username password
  do
    if [[ "$username" == "#"* ]]; then 
          # skipping commented out line 
          continue
    fi
  	#echo "username : $username"
    /opt/open-xchange/sbin/changeuser -u $username -c 10 -A oxadmin -P secret --imapserver "localhost" --smtpserver "localhost"
  	# echo "password : $password"
  done < $INPUT
  IFS=$OLDIFS
fi
if [[ "${RESTART_OX}" = true  ]]; then
  restartService dovecot
fi

