#!/bin/bash

SCRIPT_NAME=`basename $0`
APACHE_CONF_DIR=/etc/httpd
AURALIS_CONF_DIR=/etc/auralis
# the defaults file is sourced below and may override variables defined here
AURALIS_DEFAULTS_FILE=/usr/share/auralis/defaults

# Used for Apache config reset
INITIAL_CACERT_FILE=/etc/pki/tls/certs/ca-bundle.crt
INITIAL_SERVERCERT_FILE=/etc/pki/tls/certs/localhost.crt
INITIAL_SERVERCERT_KEY_FILE=/etc/pki/tls/private/localhost.key

PKI_DIR=$AURALIS_CONF_DIR/pki

CACERT_FILE=$PKI_DIR/CA/cacert.pem
CA_CHAIN_FILE=$PKI_DIR/CA/revproxy-cachain.pem
CACERT_KEY_FILE=$PKI_DIR/CA/private/cakey.pem

REVPROXY_CACERT_FILE=$PKI_DIR/CA/revproxy-cacert.pem
REVPROXY_CA_CHAIN_FILE=$PKI_DIR/CA/revproxy-cachain.pem
REVPROXY_CACERT_KEY_FILE=$PKI_DIR/CA/private/revproxy-cakey.pem

SERVERCERT_FILE=$PKI_DIR/tls/certs/servercert.pem
SERVER_CHAIN_FILE=$PKI_DIR/serverchain.pem
SERVERCERT_KEY_FILE=$PKI_DIR/tls/certs/private/serverkey.pem

CERT_FILES="$CACERT_FILE $CA_CHAIN_FILE $CACERT_KEY_FILE \
$REVPROXY_CACERT_FILE $REVPROXY_CA_CHAIN_FILE $REVPROXY_CACERT_KEY_FILE \
$SERVERCERT_FILE $SERVER_CHAIN_FILE $SERVERCERT_KEY_FILE"

# init default db config
DBHOST=localhost
DBPORT=3306
DBNAME=auralis
DBUSER=auralis

WEBROOT=/var/www/auralis

[ -f ${AURALIS_DEFAULTS_FILE} ] && . ${AURALIS_DEFAULTS_FILE}

[ -f ${AURALIS_CONF_DIR}/conf ] && . ${AURALIS_CONF_DIR}/conf || :
MYSQLROOTPASS=
DROP=false
APRESET=false

MIGRATION_VERSIONS="020100 020200 020300 020302 020305 020400 020500 020503 020504 020506 020600 020603"

rndpass() {
    dd if=/dev/urandom bs=16 count=1 2>/dev/null|base64|cut -d= -f1
}

# generate db password if not defined
[ -n "${DBPASS}" ] || DBPASS=`rndpass`

usage() {
    if [ $# -gt 0 ]; then
        echo $@ >&2
    fi
    echo "Usage: $SCRIPT_NAME [--help|-h][--config|-c <Config file>][--new|-n][--host|-h <DB host>][--port|-P <DB port>][--database|-d <DB name>][--user|-u <DB user>][--passwd|-p <DB password>][--primary-port <Port>][--secondary-port <Port>][--no-apache-reload] [--] [<MySQL root password>]" >&2
    exit 0
}

while [ $# -gt 0 ] ; do
    case "$1" in
        --new|-n)
            DROP=true
            ;;
        --apachereset|-a)
            APRESET=true
            ;;
        --host|-h)
            shift
            DBHOST=$1
            ;;
        --port|-P)
            shift
            DBPORT=$1
            ;;
        --database|-d)
            shift
            DBNAME=$1
            ;;
        --user|-u)
            shift
            DBUSER=$1
            ;;
        --passwd|-p)
            shift
            DBPASS=$1
            ;;
        --webroot|-w)
            shift
            WEBROOT=$1
            ;;
        --primary-port)
            shift
            PRIMARY_PORT=$1
            ;;
        --secondary-port)
            shift
            SECONDARY_PORT=$1
            ;;
        --no-apache-reload)
            NO_APACHE_RELOAD=1
            ;;
        --help|-h)
            usage
            ;;
        --)
            while [ $# -gt 1 ] ; do
                shift;
            done
            MYSQLROOTPASS=$1
            ;;
        *)
            MYSQLROOTPASS=$1
            ;;
    esac
    shift
done

[ -n "$DBHOST" ] || usage "database host may not be empty"
[ -n "$DBPORT" ] || usage "database port may not be empty"
[ -n "$DBNAME" ] || usage "database name may not be empty"
[ -n "$DBUSER" ] || usage "database user may not be empty"
[ -n "$DBPASS" ] || usage "database password may not be empty"

mysql_params="--host=$DBHOST --port=$DBPORT -u root --password=$MYSQLROOTPASS"

mysql_connection_failed=0
mysql_msg=$(mysql $mysql_params -e "" 2>&1)
mysql_connection_failed=$?
if [ $mysql_connection_failed -ne 0 ]; then
    mysql_connection_failed=1
    if [ -z "$MYSQLROOTPASS" ]; then
        echo -n "MySQL root password: "
        read -s MYSQLROOTPASS
        mysql_params="--host=$DBHOST --port=$DBPORT -u root --password=$MYSQLROOTPASS"
        mysql_msg=$(mysql $mysql_params -e "" 2>&1)
        mysql_connection_failed=$?
    fi
fi
if [ $mysql_connection_failed -ne 0 ]; then
    echo $mysql_msg >&2
    echo "Error: cannot connect to database" >&2
    exit 1
fi


# ensure correct user and group for $CERT_FILES. Access from apache has to
# be guaranteed by ACLs. If a file is or will be written by apache owner and
# group stays the same unless it is not replaced by a new file.
for file in $CERT_FILES; do
    [ -f $file ] || touch $file
    chown root:root $file
done

if `$DROP` ; then
    echo "drop database ${DBNAME}" | mysql $mysql_params
fi
mysql $mysql_params <<-EOF
        create database if not exists ${DBNAME} collate utf8_unicode_ci;
        connect ${DBNAME};
        grant all privileges on ${DBNAME}.* to '${DBUSER}'@localhost identified by '${DBPASS}';
EOF

cat >${AURALIS_CONF_DIR}/conf.d/database<<EOF
DBHOST=${DBHOST}
DBPORT=${DBPORT}
DBNAME=${DBNAME}
DBUSER=${DBUSER}
DBPASS=${DBPASS}
EOF

cat >${AURALIS_CONF_DIR}/conf.d/web<<EOF
WEBROOT=${WEBROOT}
EOF

chmod 0640 ${AURALIS_CONF_DIR}/conf.d/*

# clear symfony cache to get the new database config
# If the ActiveSync Filter Server database connection is not configured we get
# an error, so we use quiet mode
rm -rf /var/cache/auralis/*
auralis-console cache:warmup -q

VERSION=$(auralis-console version)

# create database schema
auralis-console doctrine:schema:update --complete --force

mysql -u ${DBUSER} --password="${DBPASS}" --host="$DBHOST" --port="$DBPORT" ${DBNAME} <<-EOF
CREATE TABLE IF NOT EXISTS config (
  id int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
  name varchar(50) NOT NULL COMMENT 'The unique key for a config value.',
  value text NOT NULL COMMENT 'The corresponding value.',
  PRIMARY KEY (id),
  UNIQUE KEY idx_config_name (name)
) ENGINE=InnoDB;

INSERT INTO config (name, value) VALUES ('version', '$VERSION') ON DUPLICATE KEY UPDATE value = value;

-- insert system admin account.
-- this account is used for MDM commands initiated by the system e.g. on rollout
SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO'; -- required to insert row with id 0
INSERT INTO admins (id, login) VALUES (0, 'SYSTEM') ON DUPLICATE KEY UPDATE id = id;
SET SESSION sql_mode=''; -- reset sql_mode

CREATE TABLE IF NOT EXISTS migration_versions (
  version varchar(255) NOT NULL,
  PRIMARY KEY (version)
) ENGINE=InnoDB;
EOF

for migration_version in $MIGRATION_VERSIONS; do
    echo "INSERT INTO migration_versions (version) VALUES ('$migration_version') ON DUPLICATE KEY UPDATE version = version;" | mysql -u ${DBUSER} --password="${DBPASS}" --host="$DBHOST" --port="$DBPORT" ${DBNAME}
done

port_changed=0;
if [ -n "$PRIMARY_PORT" ]; then
    echo "Set primary port to $PRIMARY_PORT"
    auralis-console apache:config -q --no-reload auralis_primary_port $PRIMARY_PORT
    [ $? -eq 0 ] && port_changed=1
fi
if [ -n "$SECONDARY_PORT" ]; then
    echo "Set secondary port to $SECONDARY_PORT"
    auralis-console apache:config -q --no-reload auralis_secondary_port $SECONDARY_PORT
    [ $? -eq 0 ] && port_changed=1
fi

# refresh apache config
echo "Refresh Apache HTTPD configuration"
auralis-console apache:config:refresh -q
if [ $? -eq 64 ] && [ $port_changed -eq 1 ] && [ ! `$APRESET` ] && [ "$NO_APACHE_RELOAD" -ne 1 ]; then
    # refresh didn't change config, but ports have been changed, so restart
    # Apache here
    # if APRESET is true Apache will be restarted below
    areload && arestart
fi

if `$APRESET` ; then
    echo "Reset Apache HTTPD configuration"
    : > ${APACHE_CONF_DIR}/auralis.d/hostname
    if [ -f ${INITIAL_SERVERCERT_FILE} ] && [ -f ${INITIAL_SERVERCERT_KEY_FILE} ]; then
        cat >${APACHE_CONF_DIR}/auralis.d/servercert<<EOF
SSLCertificateFile ${INITIAL_SERVERCERT_FILE}
SSLCertificateKeyFile ${INITIAL_SERVERCERT_KEY_FILE}
EOF
    fi
    if [ -f ${INITIAL_CACERT_FILE} ]; then
        cat >${APACHE_CONF_DIR}/auralis.d/clientca<<EOF
SSLCACertificateFile ${INITIAL_CACERT_FILE}
EOF
    fi
    cat >${APACHE_CONF_DIR}/auralis.d/reloadcookie<<EOF
SetEnv RELOAD_COOKIE 0
EOF
    cat >${APACHE_CONF_DIR}/auralis.d/allowfrom<<EOF
Allow from all
EOF
    cat >${APACHE_CONF_DIR}/auralis.d/listen<<EOF
Listen \${auralis_primary_port}
Listen \${auralis_secondary_port}
EOF
    cat >${APACHE_CONF_DIR}/auralis.d/reverse_proxy<<EOF
Include auralis.d/reverse_proxy.d/*
EOF
    cat >${APACHE_CONF_DIR}/auralis.d/activesyncfilter<<EOF
<IfModule mod_activesync.c>
    SetOutputFilter INFLATE;ACTIVESYNC;DEFLATE
    ActiveSyncOptions FilterHost=\${activesyncfilter_host} FilterPort=\${activesyncfilter_port} MinWbxmlLen=10240 SocketTimeout=60000
</IfModule>
EOF
    : > /etc/auralis/pki/CA/index.txt
    : > ${APACHE_CONF_DIR}/auralis.d/clientcrl
    : > ${APACHE_CONF_DIR}/auralis.d/proxysetup
    find ${APACHE_CONF_DIR}/auralis.d -type f | xargs chmod 0640
    find ${APACHE_CONF_DIR}/auralis.d -type d | xargs chmod 0750
    if [ "$NO_APACHE_RELOAD" -ne 1 ]; then
        areload && arestart
    fi
fi
