#!/bin/bash

set -o errexit
set -o pipefail
set -o nounset

#set -x

PILER_HOSTNAME="${PILER_HOSTNAME:-archive.yourdomain.com}"
MYSQL_ROOT_PASSWORD="${MYSQL_ROOT_PASSWORD:-abcde123}"
MYSQL_PILER_PASSWORD="${MYSQL_PILER_PASSWORD:-piler123}"
ENCRYPT_MYSQL_DATA_AT_REST=1
AUTH_CODE="${AUTH_CODE:-fNNJADYT0EILtrD7hxh}"
NODE_TYPE=${NODE_TYPE:-WORKER}
PRIMARY_MASTER="${PRIMARY_MASTER:-0}"
MULTITENANCY=${MULTITENANCY:-0}
MULTINODES=${MULTINODES:-0}
MASTER_NODE=${MASTER_NODE:-10.1.1.2}
SERVER_ID=${SERVER_ID:-0}
USE_SMTP_GATEWAY=${USE_SMTP_GATEWAY:-0}
SPHINX_WORKER_LISTEN_ADDRESS="${SPHINX_WORKER_LISTEN_ADDRESS:-}"
PHP_FPM_SOCKET="/var/run/php-fpm/www.sock"
RT=${RT:-1}

PILER_VERSION="1.8.2"

MYSQL_HOSTNAME="localhost"
MYSQL_DATABASE="piler"
MYSQL_USERNAME="piler"

APACHE_TIKA="tika-server-standard-2.6.0.jar"
DOWNLOAD_URL="https://download.mailpiler.com"
COMMIT_ID="$(curl -k -s ${DOWNLOAD_URL}/piler-ee/piler-ee.tag)"
PILER_RPM="piler-ee-${PILER_VERSION}-${COMMIT_ID}.el9.x86_64.rpm"

PILER_USER="piler"
PILER_CONF="/etc/piler/piler.conf"
CONFIG_SITE_PHP="/etc/piler/config-site.php"


install_prerequisites() {
   #sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
   #sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*

   yum update -y

   dnf install -y https://rpms.remirepo.net/enterprise/remi-release-9.rpm
   rpm -qa | grep remi
   dnf module list -y php
   dnf module enable -y php:remi-8.1

   yum install -y tar rsyslog memcached which gettext wget unzip mariadb-server mariadb-common python3 python3-pip make sysstat bzip2 java-11-openjdk curl nginx unixODBC libzip zip libtool-ltdl php-cli php-common php-fpm php-json php-gd php-ldap php-mbstring php-mysqlnd php-pdo php-xml php-pecl-zip php-pecl-memcached nmap-ncat tre-devel jq
   pip3 install "${DOWNLOAD_URL}/generic-local/mysqlclient-2.1.1-cp39-cp39-linux_x86_64.whl"
   pip3 install imapclient minio==7.1.12
   yum install -y https://repo.manticoresearch.com/manticore-repo.noarch.rpm
   yum install -y manticore manticore-columnar-lib manticore-extra
   systemctl stop manticore
   systemctl disable manticore

   echo "apache ALL=NOPASSWD: /usr/bin/systemctl restart piler" >> /etc/sudoers
}


setup_mysql_encryption() {
   local s
   local encrypt_cfg_dir="/etc/my.cnf.d/encrypt"

   ### See https://mariadb.com/kb/en/file-key-management-encryption-plugin/ for more

   mkdir -p "$encrypt_cfg_dir"
   chown mysql:mysql "$encrypt_cfg_dir"
   chmod 700 "$encrypt_cfg_dir"
   s="$(openssl rand -hex 32)"
   echo "1;${s}" > "${encrypt_cfg_dir}/keyfile"
   openssl rand -hex 128 > "${encrypt_cfg_dir}/keyfile.key"
   openssl enc -aes-256-cbc -md sha1 -pass file:"${encrypt_cfg_dir}/keyfile.key" -in "${encrypt_cfg_dir}/keyfile" -out "${encrypt_cfg_dir}/keyfile.enc"
   rm -f "${encrypt_cfg_dir}/keyfile"

   cat > /etc/my.cnf.d/99-encrypt.cnf << ENCRYPT_CNF
[mariadb]

plugin_load_add = file_key_management
loose_file_key_management_filename = ${encrypt_cfg_dir}/keyfile.enc
loose_file_key_management_filekey = FILE:${encrypt_cfg_dir}/keyfile.key
loose_file_key_management_encryption_algorithm = AES_CBC
ENCRYPT_CNF

}


start_mysql() {
   [[ $ENCRYPT_MYSQL_DATA_AT_REST -eq 1 ]] && setup_mysql_encryption

   if [[ -f /.dockerenv ]]; then
      mysqld_safe &
      sleep 5
   else
      systemctl restart mariadb
   fi

   mysqladmin -u root password "$MYSQL_ROOT_PASSWORD"
}


install_piler() {
   groupadd piler || true
   useradd -g piler -d /var/piler -s /bin/bash  piler || true

   yum install -y "${DOWNLOAD_URL}/piler-ee/${PILER_RPM}"
   ldconfig

   if test "$NODE_TYPE" = "MASTER"; then
      sed -i 's/#CREATE_CUSTOMER/1,16,31,46/' /usr/share/piler/piler.cron
      sed -i 's/#ON_GUI//g' /usr/share/piler/piler.cron
   else
      sed -i 's/#CREATE_CUSTOMER/20/' /usr/share/piler/piler.cron
      sed -i 's/#ON_WORKER//g' /usr/share/piler/piler.cron
   fi

   crontab -u $PILER_USER /usr/share/piler/piler.cron

   ln -sf /etc/piler/piler-nginx.conf /etc/nginx/conf.d/piler.conf
   wget -q -O "/var/piler/tika/tika-server.jar" "${DOWNLOAD_URL}/generic-local/${APACHE_TIKA}"

   if [[ $ENCRYPT_MYSQL_DATA_AT_REST -eq 1 ]]; then
      touch /etc/piler/ENCRYPTED_DATABASE
   fi

   if [[ $RT -eq 1 ]]; then
      sed -i 's/.*indexer.*\.sh/###/g' /usr/share/piler/piler.cron
   fi

   touch /etc/piler/MANTICORE

   echo "piler ALL=NOPASSWD: /usr/bin/systemctl restart pilersearch" >> /etc/sudoers

   chgrp apache /var/piler/export
}


create_my_cnf() {
   local user=$1
   local password=$2
   local my_cnf=$3

   printf "[mysql]\\n\\nhost = %s\\nuser = %s\\npassword = %s\\n" "$MYSQL_HOSTNAME" "$user" "$password" > "$my_cnf"
   printf "\\n\\n[mysqldump]\\n\\nhost = %s\\nuser = %s\\npassword = %s\\n" "$MYSQL_HOSTNAME" "$user" "$password" >> "$my_cnf"

   chown $PILER_USER:$PILER_USER "$my_cnf"
   chmod 600 "$my_cnf"
}


fix_config_site_php() {
   sed -i -e "s%HOSTNAME%${PILER_HOSTNAME}%g" -e "s%MYSQL_PASSWORD%${MYSQL_PILER_PASSWORD}%g" "$CONFIG_SITE_PHP"

   if [[ $MULTITENANCY -eq 1 ]]; then
      sed -i "s%\$config\\['MULTITENANCY'\\] = 0%\$config\\['MULTITENANCY'\\] = 1%" "$CONFIG_SITE_PHP"
   fi

   {
      echo "\$config['SERVER_ID'] = $SERVER_ID;"
      echo "\$config['USE_SMTP_GATEWAY'] = $USE_SMTP_GATEWAY;"
      echo "\$config['ENABLE_MEMCACHED'] = 1;"
      echo "\$config['TIMEZONE'] = 'Europe/Budapest';"
   } >> "$CONFIG_SITE_PHP"

   if [[ "$SPHINX_WORKER_LISTEN_ADDRESS" ]]; then
      echo "\$config['SPHINX_WORKER_LISTEN_ADDRESS'] = '$SPHINX_WORKER_LISTEN_ADDRESS';" >> "$CONFIG_SITE_PHP"
   fi

   if [[ $MULTINODES -eq 1 ]]; then
      sed -i "s%\$config\\['MULTINODES'\\] = 0%\$config\\['MULTINODES'\\] = 1%" "$CONFIG_SITE_PHP"

      echo "\$config['AUTH_CODE'] = '$AUTH_CODE';" >> "$CONFIG_SITE_PHP"
      echo "\$config['PRIMARY_MASTER'] = $PRIMARY_MASTER;" >> "$CONFIG_SITE_PHP"

      if test "$NODE_TYPE" = "MASTER"; then
         echo "\$config['NODE_TYPE'] = MASTER;" >> "$CONFIG_SITE_PHP"
      else
         echo "\$config['MASTER_NODE'] = '$MASTER_NODE';" >> "$CONFIG_SITE_PHP"
      fi
   else
      echo "\$config['ARCHIVE_HOST'] = '$PILER_HOSTNAME';" >> "$CONFIG_SITE_PHP"
   fi

   if [[ $RT -eq 1 ]]; then
      echo "\$config['RT_INDEX'] = 1;" >> "$CONFIG_SITE_PHP"
   fi
}


save_node_type() {
   echo "$NODE_TYPE" > "/etc/piler/${NODE_TYPE}"
}

save_multinodes_settings() {
   if [[ $MULTINODES -eq 1 ]]; then
      touch /etc/piler/MULTINODES
   fi
}

init_db() {
   sed -e "s%MYSQL_HOSTNAME%${MYSQL_HOSTNAME}%g" \
       -e "s%MYSQL_DATABASE%${MYSQL_DATABASE}%g" \
       -e "s%MYSQL_USERNAME%${MYSQL_USERNAME}%g" \
       -e "s%MYSQL_PASSWORD%${MYSQL_PILER_PASSWORD}%g" \
      /usr/share/piler/db-mysql-root.sql.in | mysql -h "$MYSQL_HOSTNAME"

   if [[ $ENCRYPT_MYSQL_DATA_AT_REST -eq 1 ]]; then
      sed 's/Engine=InnoDB/ENGINE=InnoDB ENCRYPTED=YES/ig' /usr/share/piler/db-mysql.sql | mysql --defaults-file=/etc/piler/.my.cnf -h "$MYSQL_HOSTNAME" "$MYSQL_DATABASE"
   else
      mysql --defaults-file=/etc/piler/.my.cnf -h "$MYSQL_HOSTNAME" "$MYSQL_DATABASE" < /usr/share/piler/db-mysql.sql
   fi

}


get_the_licence() {
   echo "Get the license file, and copy it to /etc/piler/piler.lic"
   echo "Then reboot the host"
}


add_systemd_services() {
   pushd /etc/systemd/system

   ln -sf /usr/libexec/piler/piler.service .
   ln -sf /usr/libexec/piler/piler-smtp.service .
   ln -sf /usr/libexec/piler/pilersearch.service .
   ln -sf /usr/libexec/piler/tika.service .

   popd

   systemctl daemon-reload

   systemctl enable piler
   systemctl enable piler-smtp
   systemctl enable pilersearch
   systemctl enable tika
}


create_default_tenant() {
   local PILERHOME=/var/piler
   local CUSTOMERID="piler"
   local SERVERID
   local sphinxdir="manticore"

   SERVERID=$(printf "%02x" "$SERVER_ID")

   echo "creating default tenant"

   if [[ ! -d "${PILERHOME}/store/${SERVERID}/${CUSTOMERID}" ]]; then
      mkdir -p "${PILERHOME}/store/${SERVERID}/${CUSTOMERID}"
      mkdir -p "${PILERHOME}/astore/${SERVERID}/${CUSTOMERID}"
      chown -R "${PILER_USER}:${PILER_USER}" "${PILERHOME}/store"
      chown -R "${PILER_USER}:${PILER_USER}" "${PILERHOME}/astore"
   fi

   if [[ ! -d "${PILERHOME}/${sphinxdir}/${CUSTOMERID}" ]]; then
      mkdir -p "${PILERHOME}/${sphinxdir}/${CUSTOMERID}"
      chown "${PILER_USER}:${PILER_USER}" "${PILERHOME}/${sphinxdir}/${CUSTOMERID}"
      chmod 700 "${PILERHOME}/${sphinxdir}/${CUSTOMERID}"

      if [[ $RT -eq 0 ]]; then
         echo "creating index files"

         echo main1 > "${PILERHOME}/${sphinxdir}/${CUSTOMERID}/MAIN"

         [[ -f "/etc/piler/MASTER" ]] || { indexer --quiet --config /etc/piler/manticore.conf \
                                                 "${CUSTOMERID}_main1" \
                                                 "${CUSTOMERID}_dailydelta1" \
                                                 "${CUSTOMERID}_delta1" \
                                                 "${CUSTOMERID}_tag1" \
                                                 "${CUSTOMERID}_note1"; chown -R "${PILER_USER}:${PILER_USER}" /var/piler/manticore; }
      fi
   fi
}


write_goss_vars() {
cat >/etc/piler/vars.yaml <<EOF
pilerhost: "$PILER_HOSTNAME"
nodetype: "$NODE_TYPE"
multitenancy: $MULTITENANCY
multinodes: $MULTINODES
EOF
}


centos_notes() {
   echo
   echo "Centos specific notes:"
   echo " * Be sure to either disable selinux or add the required rules"
}


install_prerequisites

start_mysql

install_piler

create_my_cnf "root" "${MYSQL_ROOT_PASSWORD}" /etc/piler/.my.cnf-root
create_my_cnf "piler" "${MYSQL_PILER_PASSWORD}" /etc/piler/.my.cnf
cp /etc/piler/.my.cnf-root /root/.my.cnf

fix_config_site_php

if [[ "$NODE_TYPE" == "WORKER" ]]; then add_systemd_services; fi

systemctl enable --now php-fpm
systemctl enable nginx
systemctl enable --now mariadb
systemctl enable --now memcached


if [[ ! -f /etc/piler/piler-nginx.conf ]]; then
   sed -e "s%HOSTNAME%$PILER_HOSTNAME%g" -e "s%PHP_FPM_SOCKET%$PHP_FPM_SOCKET%g" /etc/piler/piler-nginx.conf.dist > /etc/piler/piler-nginx.conf
   nginx -t
   service nginx restart
fi

if [[ ! -f "$PILER_CONF" ]]; then
   sed -e "s/verystrongpassword/$MYSQL_PILER_PASSWORD/g" -e "s/piler.yourdomain.com/$PILER_HOSTNAME/g" "${PILER_CONF}.dist" > "$PILER_CONF"
   sed -i 's/^mysqlsocket=.*/mysqlsocket=\/var\/lib\/mysql\/mysql\.sock/' "$PILER_CONF"

   chmod 600 "$PILER_CONF"
   chown $PILER_USER:$PILER_USER "$PILER_CONF"

   if [[ $RT -eq 1 ]]; then
      sed -i "s%rtindex=.*%rtindex=1%" "$PILER_CONF"
   fi
fi


if [[ "$NODE_TYPE" == WORKER || $PRIMARY_MASTER -eq 1 ]]; then
   init_db
fi

save_node_type
save_multinodes_settings

if pgrep firewalld; then
   firewall-cmd --add-service=http --permanent
fi

[[ ! -d /var/run/piler ]] || mkdir -p /var/run/piler

systemctl start pilersearch
systemctl start tika

[[ $MULTITENANCY -eq 1 ]] || create_default_tenant

get_the_licence

write_goss_vars

centos_notes
