#!/bin/bash

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

#set -x

# Detect platform
detect_platform() {
    if command -v apt-get >/dev/null 2>&1 || command -v apt >/dev/null 2>&1; then
        echo "ubuntu"
    elif command -v yum >/dev/null 2>&1 || command -v dnf >/dev/null 2>&1; then
        echo "centos"
    else
        echo "ERROR: Unsupported platform. Neither apt-get nor yum/dnf found." >&2
        exit 1
    fi
}

DISTRO_TYPE=$(detect_platform)
echo "Detected platform: $DISTRO_TYPE"

# Common configuration variables
PILER_HOSTNAME="${PILER_HOSTNAME:-archive.example.com}"
MYSQL_ROOT_PASSWORD="${MYSQL_ROOT_PASSWORD:-abcde123}"
MYSQL_PILER_PASSWORD="${MYSQL_PILER_PASSWORD:-piler123}"
ENCRYPT_MYSQL_DATA_AT_REST=1
NODE_TYPE="${NODE_TYPE:-MASTER}"
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:-}"
PILER_VERSION="2.1.0"

ARCH="${ARCH:-amd64}"

SELF_SIGNED_CERT=0

MANTICORE_WORKERS="" ## Only in multinodes environment!

COMMIT_ID="5cc33fe"

DOWNLOAD_URL="https://download.mailpiler.com"

# Platform-specific package names
if [[ "$DISTRO_TYPE" == "ubuntu" ]]; then
    export DEBIAN_FRONTEND=noninteractive
    PILER_DEB="piler-ee_2.1.0-${COMMIT_ID}-noble_${ARCH}.deb"
    PILER_SMTP_DEB="piler-smtp_2.1.0-8fe23d4-noble_${ARCH}.deb"
else
    RPM_ARCH="x86_64"
    if [[ "$ARCH" == "arm64" ]]; then
        RPM_ARCH="aarch64"
    fi
    PILER_RPM="piler-ee-2.1.0-1.${COMMIT_ID}.el10.${RPM_ARCH}.rpm"
    PILER_SMTP_RPM="piler-smtp-2.1.0-1.8fe23d4.el10.${RPM_ARCH}.rpm"
fi

# Common variables from common.sh
SSL_CERT_DATA="/C=US/ST=Denial/L=Springfield/O=Dis/CN=${PILER_HOSTNAME}"
PILER_ENV_FILE="/var/piler/.env"
PILER_USER="piler"
TIKA_VERSION="3.2.1"
TRAEFIK_VERSION="v3.5.2"
MANTICORE_HOST="127.0.0.1"
MYSQL_HOSTNAME="localhost"
MYSQL_DATABASE="piler"

#
# Platform-specific functions
#

install_prerequisites_ubuntu() {
    echo "${FUNCNAME[0]}"

    apt-get update
    apt-get -y --no-install-recommends install wget curl gnupg rsyslog openssl sysstat unzip sudo libtre5 libzip4t64 zip libmariadb-dev mariadb-server cron openjdk-21-jre redis netcat-openbsd jq libsodium23
    curl -L -o manticore-repo.noarch.deb https://repo.manticoresearch.com/manticore-repo.noarch.deb
    dpkg -i manticore-repo.noarch.deb
    apt-get update
    apt-get install -y manticore manticore-columnar-lib manticore-extra
    [[ -f /.dockerenv ]] || systemctl stop manticore
}

install_prerequisites_centos() {
    echo "${FUNCNAME[0]}"

    #yum update -y

    yum install -y tar crontabs rsyslog openssl valkey which gettext unzip mariadb-server mariadb-common make sysstat bzip2 java-21-openjdk curl unixODBC libzip zip libtool-ltdl nmap-ncat jq
    yum install -y https://repo.manticoresearch.com/manticore-repo.noarch.rpm
    yum install -y manticore manticore-columnar-lib manticore-extra

    if [[ ! -f /.dockerenv ]]; then
        systemctl stop manticore
        systemctl disable manticore
    fi

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

    echo "/usr/local/lib" > /etc/ld.so.conf.d/tre.conf
    ldconfig
}

fix_mysql_settings() {
    echo "${FUNCNAME[0]}"

    cat > /etc/mysql/mariadb.conf.d/99-piler.cnf << 'PILER_CNF'
[mysqld]

innodb_buffer_pool_size=512M
innodb_flush_log_at_trx_commit=1
innodb_log_buffer_size=64M
innodb_log_file_size=64M
innodb_read_io_threads=4
innodb_write_io_threads=4
innodb_log_files_in_group=2

innodb_file_per_table
PILER_CNF
}

start_mysql_ubuntu() {
    echo "${FUNCNAME[0]}"

    fix_mysql_settings
    [[ $ENCRYPT_MYSQL_DATA_AT_REST -eq 1 ]] && setup_mysql_encryption_ubuntu

    service mariadb restart
    mysqladmin -u root password "${MYSQL_ROOT_PASSWORD}"
}

start_mysql_centos() {
    echo "${FUNCNAME[0]}"

    [[ $ENCRYPT_MYSQL_DATA_AT_REST -eq 1 ]] && setup_mysql_encryption_centos

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

    mysqladmin -u root password "$MYSQL_ROOT_PASSWORD"
}

install_piler_ubuntu() {
    echo "${FUNCNAME[0]}"

    curl -Lo "$PILER_DEB" "${DOWNLOAD_URL}/piler-ee/${PILER_VERSION}/${PILER_DEB}"
    curl -Lo "$PILER_SMTP_DEB" "${DOWNLOAD_URL}/piler-smtp/${PILER_SMTP_DEB}"
    dpkg -i "$PILER_SMTP_DEB"
    dpkg -i "$PILER_DEB"
}

install_piler_centos() {
    echo "${FUNCNAME[0]}"

    groupadd piler || true
    useradd -g piler -d /var/piler -s /bin/bash piler || true

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

centos_notes() {
    echo "${FUNCNAME[0]}"

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

#
# Common functions (from common.sh)
#

fix_piler_conf() {
    echo "${FUNCNAME[0]}"

    if [[ ! -f /etc/piler/piler.conf ]]; then
        cp /etc/piler/piler.conf.dist /etc/piler/piler.conf
        chown root:piler /etc/piler/piler.conf
    fi

    if [[ ! -f /etc/piler/manticore.sql ]]; then
        cp /etc/piler/manticore.sql.dist /etc/piler/manticore.sql
    fi

    if [[ ! -f /etc/piler/manticore.conf ]]; then
        cp /etc/piler/manticore.conf.dist /etc/piler/manticore.conf
    fi
}

make_certificate() {
    local pemfile="/etc/piler/piler.pem"

    echo "${FUNCNAME[0]}"

    if [[ ! -f "$pemfile" ]]; then
        echo "Making an ssl certificate"
        openssl req -new -newkey rsa:4096 -days 3650 -nodes -x509 -subj "$SSL_CERT_DATA" -keyout "$pemfile" -out "1.cert" -sha256 2>/dev/null
        cat 1.cert >> "$pemfile"
        rm -f 1.cert
        chown root:piler "$pemfile"
        chmod 640 "$pemfile"
    fi
}

make_piler_key() {
    local keyfile="/etc/piler/piler.key"

    echo "${FUNCNAME[0]}"

    if [[ ! -f "$keyfile" ]]; then
        echo "Generating piler.key"
        dd if=/dev/urandom bs=64 count=1 of="$keyfile" 2>/dev/null
        [[ $(stat -c '%s' "$keyfile") -eq 64 ]] || {
            echo "ERROR: could not read 64 bytes from /dev/urandom to $keyfile" >&2
            exit 1
        }
        chown root:piler "$keyfile"
        chmod 640 "$keyfile"
    fi
}

init_db() {
    echo "${FUNCNAME[0]}"

    echo "create database piler character set utf8mb4 collate=utf8mb4_unicode_ci;" \
         "grant all privileges on piler.* to piler@localhost identified by '${MYSQL_PILER_PASSWORD}'; " \
         "flush privileges; " | mariadb --defaults-file=/etc/piler/.my.cnf-root -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
}

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

    echo "${FUNCNAME[0]}"

    ### 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 = /etc/my.cnf.d/encrypt/keyfile.enc
loose_file_key_management_filekey = FILE:/etc/my.cnf.d/encrypt/keyfile.key
loose_file_key_management_encryption_algorithm = AES_CBC
ENCRYPT_CNF

}

setup_mysql_encryption_ubuntu() {
    local s
    local encrypt_cfg_dir="/etc/mysql/encrypt"

    echo "${FUNCNAME[0]}"

    ### 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/mysql/mariadb.conf.d/99-encrypt.cnf << 'ENCRYPT_CNF'
[mariadb]

plugin_load_add = file_key_management
loose_file_key_management_filename = /etc/mysql/encrypt/keyfile.enc
loose_file_key_management_filekey = FILE:/etc/mysql/encrypt/keyfile.key
loose_file_key_management_encryption_algorithm = AES_CBC
ENCRYPT_CNF
}

install_piler_ui() {
    local cronfile="/usr/share/piler/cron.jobs-2.x"

    echo "${FUNCNAME[0]}"

    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

    mkdir -p /var/piler/manticore
    chown piler:piler /var/piler/manticore

    if [[ "$NODE_TYPE" == "MASTER" && $MULTINODES -eq 1 ]]; then
        sed -i 's/#CREATE_CUSTOMER/1,16,31,46/' "$cronfile"
        sed -i 's/#ON_GUI//g' "$cronfile"
    else
        sed -i 's/#CREATE_CUSTOMER/20/' "$cronfile"
        sed -i 's/#ON_WORKER//g' "$cronfile"
    fi

    crontab -u "$PILER_USER" "$cronfile"

    mkdir -p /var/piler/tika
    curl -L -o "/var/piler/tika/tika-server.jar" "https://download.mailpiler.com/tika-server-standard-${TIKA_VERSION}.jar"

    mkdir -p /var/piler/s3
    chown piler:piler /var/piler/s3

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

    touch /etc/piler/MANTICORE

    touch /etc/piler/MANTICORE_DYNAMIC

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

    mkdir -p /var/piler/export
    chgrp piler /var/piler/export

    make_certificate
    make_piler_key
}

install_onnx_lib() {
    local ONNX_VERSION="1.23.2"
    local ONNX_ARCH

    echo "${FUNCNAME[0]}"

    if [[ $ARCH == "amd64" ]]; then
        ONNX_ARCH="x64"
    else
        ONNX_ARCH="aarch64"
    fi

    curl -L -o "onnxruntime-linux-${ONNX_ARCH}-${ONNX_VERSION}.tgz" "https://download.mailpiler.com/generic-local/onnxruntime-linux-${ONNX_ARCH}-${ONNX_VERSION}.tgz"

    tar -xzf "onnxruntime-linux-${ONNX_ARCH}-${ONNX_VERSION}.tgz"

    cp "onnxruntime-linux-${ONNX_ARCH}-${ONNX_VERSION}/lib/libonnxruntime.so.1.23.2" /usr/local/lib/
    cp "onnxruntime-linux-${ONNX_ARCH}-${ONNX_VERSION}/lib/libonnxruntime_providers_shared.so" /usr/local/lib/

    pushd /usr/local/lib >/dev/null
    ln -sf libonnxruntime.so.1.23.2 libonnxruntime.so.1
    ln -sf libonnxruntime.so.1.23.2 libonnxruntime.so
    ln -sf libonnxruntime.so.1.23.2 onnxruntime.so.1.23.2
    ln -sf libonnxruntime.so.1.23.2 onnxruntime.so.1
    ln -sf libonnxruntime.so.1.23.2 onnxruntime.so
    popd >/dev/null

    rm -f "onnxruntime-linux-${ONNX_ARCH}-${ONNX_VERSION}.tgz"
    rm -rf "onnxruntime-linux-${ONNX_ARCH}-${ONNX_VERSION}"

    echo "ONNX Runtime ${ONNX_VERSION} installed for ${ONNX_ARCH}"
}

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

    echo "${FUNCNAME[0]}"

    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"
}

save_node_type() {
    echo "${FUNCNAME[0]}"

    echo "$NODE_TYPE" > "/etc/piler/${NODE_TYPE}"
}

save_multinodes_settings() {
    echo "${FUNCNAME[0]}"

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

add_systemd_services() {
    echo "${FUNCNAME[0]}"

    if [[ ! -f /.dockerenv ]]; then
        systemctl daemon-reload

        systemctl enable piler
        systemctl enable piler-scanner
        systemctl enable piler-smtp
        systemctl enable piler-ui
        systemctl enable piler-search
        systemctl enable tika
        systemctl enable traefik
    fi
}

get_model() {
    echo "${FUNCNAME[0]}"

    mkdir -p /var/piler/models/all-MiniLM-L6-v2-onnx
    pushd /var/piler/models/all-MiniLM-L6-v2-onnx

    for i in config.json model.onnx tokenizer.json; do
        curl -L -o "$i" "https://download.mailpiler.com/all-MiniLM-L6-v2-onnx/${i}"
    done

    popd
}

write_ui_config() {
    echo "${FUNCNAME[0]}"

    if [[ ! -f "$PILER_ENV_FILE" ]]; then

        cat > "$PILER_ENV_FILE" << PILER_ENV_FILE
LICENSE_FILE=/etc/piler/license.jwt
LISTEN_ADDR=127.0.0.1:3000
NODE_TYPE=master
MYSQL_USER=piler
MYSQL_PASSWORD=$MYSQL_PILER_PASSWORD
MYSQL_HOST=localhost:3306

MANTICORE_DSN=piler:piler123@tcp(localhost:9306)/?parseTime=true
MANTICORE_READONLY_DSN=piler:piler123@tcp(localhost:9307)/?parseTime=true
REDIS_ADDR=localhost:6379
LANGUAGES=de,en,es,fr,zh
TRACE_ADDR=127.0.0.1:4317

LOG_LEVEL=INFO
NOREPLY_EMAIL=no-reply@$PILER_HOSTNAME

DATE_FORMAT=YYYY/MM/DD
TIMEZONE=Europe/Budapest

DIR_EXPORT=/var/piler/export

ENABLE_DELETE=true
NEED_TO_APPROVE_DELETE=false

PILER_THREADS=3

ML_PHISHING_ENABLED=true
ML_PHISHING_THRESHOLD=0.5
SECURITY_RISK_ENABLED=true
COMPLIANCE_RISK_ENABLED=true
SCAN_RATE_LIMIT=1000
SMART_INSIGHTS_ENABLED=true
SCANNER_THREADS=2

SEMANTIC_SEARCH_MODEL_PATH=/var/piler/models/all-MiniLM-L6-v2-onnx
SEMANTIC_SEARCH_ENABLED=true
SEMANTIC_SEARCH_DIMENSIONS=384
SEMANTIC_SEARCH_USE_TOKEN_TYPES=true
SEMANTIC_SEARCH_MAX_TOKENS=1000
SEMANTIC_SEARCH_SCORE_THRESHOLD=0.55

PILER_ENV_FILE

    fi
}

setup_traefik() {
    echo "${FUNCNAME[0]}"

    curl -L -o "traefik_${TRAEFIK_VERSION}_linux_${ARCH}.tar.gz" "https://github.com/traefik/traefik/releases/download/${TRAEFIK_VERSION}/traefik_${TRAEFIK_VERSION}_linux_${ARCH}.tar.gz"
    tar zxvf "traefik_${TRAEFIK_VERSION}_linux_${ARCH}.tar.gz" traefik
    chown root:root traefik
    chmod 755 traefik
    mv traefik /usr/local/bin
    setcap cap_net_bind_service+ep /usr/local/bin/traefik
    curl -L -o /etc/systemd/system/traefik.service "${DOWNLOAD_URL}/generic-local/traefik.service"
    groupadd traefik || true
    useradd -g traefik -s /bin/false traefik || true

    curl -L -o /etc/systemd/system/traefik.service "${DOWNLOAD_URL}/generic-local/traefik.service"

    sed -i 's/www-data/traefik/g' /etc/systemd/system/traefik.service

    mkdir -p /usr/local/etc/traefik
    touch /usr/local/etc/traefik/acme.json
    chmod 600 /usr/local/etc/traefik/acme.json
    chown traefik:traefik /usr/local/etc/traefik/acme.json

    cat > /usr/local/etc/traefik/traefik.yaml << TRAEFIK
log:
  level: INFO

entryPoints:
  websecure:
    address: ":443"

providers:
  file:
    filename: "/usr/local/etc/traefik/traefik.yaml"

certificatesResolvers:
  le:
    acme:
      storage: "/usr/local/etc/traefik/acme.json"
      email: admin@$PILER_HOSTNAME
      tlsChallenge: {}

tls:
  options:
    default:
      minVersion: VersionTLS13

http:
  middlewares:
    piler_headers:
      headers:
        customResponseHeaders:
          Server: ""
          Strict-Transport-Security: "max-age=31536000; includeSubDomains"
          X-Content-Type-Options: "nosniff"
          Referrer-Policy: "same-origin"
  routers:
    master:
      rule: "Host(\`$PILER_HOSTNAME\`)"
      service: www
      middlewares:
        - "piler_headers"
      tls:
        certResolver: le
  services:
    www:
      loadBalancer:
        servers:
        - url: "http://127.0.0.1:3000/"
TRAEFIK

    if [[ $SELF_SIGNED_CERT -eq 1 ]]; then
        mkdir -p /var/piler/ui/certs
        openssl req -x509 -newkey rsa:4096 -nodes -days 365 -keyout /var/piler/ui/certs/selfsigned.key -out /var/piler/ui/certs/selfsigned.crt -subj "/CN=${PILER_HOSTNAME}"
        chown traefik /var/piler/ui/certs/selfsigned.key
        cat > /usr/local/etc/traefik/traefik.yaml << 'TRAEFIK_SELF_SIGNED'
log:
  level: INFO

entryPoints:
  websecure:
    address: ":443"

providers:
  file:
    filename: "/usr/local/etc/traefik/traefik.yaml"

tls:
  certificates:
    - certFile: /var/piler/ui/certs/selfsigned.crt
      keyFile: /var/piler/ui/certs/selfsigned.key

http:
  middlewares:
    piler_headers:
      headers:
        customResponseHeaders:
          Server: ""
          Strict-Transport-Security: "max-age=31536000; includeSubDomains"
          X-Content-Type-Optionsi: "nosniff"
          Referrer-Policy: "same-origin"
  routers:
    master:
      rule: "Host(\`$PILER_HOSTNAME\`)"
      service: www
      middlewares:
        - "piler_headers"
      tls: {}
  services:
    www:
      loadBalancer:
        servers:
        - url: "http://127.0.0.1:3000/"
TRAEFIK_SELF_SIGNED
    fi
}

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

    echo "${FUNCNAME[0]}"

    # shellcheck disable=SC2153
    SERVERID=$(printf "%02x" "$SERVER_ID")

    echo "creating default tenant"

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

    if [[ ! -d "${PILERHOME}/${sphinxdir}/${TENANTID}" ]]; then
        if [[ -f /etc/piler/MASTER && $MULTINODES -eq 1 ]]; then
            if ! mysql -N -h "$MANTICORE_HOST" -P9306 <<< "SHOW INDEX ${TENANTID} STATUS" 2>/dev/null; then
                /usr/libexec/piler/print-master-node-index.sh "$MANTICORE_WORKERS" "$TENANTID" | mysql -h "$MANTICORE_HOST" -P9306
            fi
        else
            sed "s/TENANTID/${TENANTID}/g" /etc/piler/manticore.sql | mysql -h "$MANTICORE_HOST" -P9306
        fi
        logger -i -t piler/create-tenant mail.info <<< "Created index for ${TENANTID}"
    fi

    mariadb "--defaults-file=/etc/piler/.my.cnf" "$MYSQL_DATABASE" <<< "insert into tenant_settings (tenant_id, gui_url, tenant_address, domain, retention_days, status) values('piler', '${PILER_HOSTNAME}', 'piler@admin', 'piler.fu', 7300, 'OK')"

}

get_the_licence() {
    echo "${FUNCNAME[0]}"

    curl -L -s -o /etc/piler/license.pub https://download.mailpiler.com/license.pub

    echo "Get the license, and copy it to /etc/piler/license.jwt!"
    echo "Finally reboot the host"
}

#
# Main installation flow
#

echo "Starting Piler installation for $DISTRO_TYPE..."

# Platform-specific installation
if [[ "$DISTRO_TYPE" == "ubuntu" ]]; then
    install_prerequisites_ubuntu
    install_onnx_lib

    start_mysql_ubuntu

    install_piler_ubuntu
    install_piler_ui

    fix_piler_conf

    init_db

    save_node_type
    write_ui_config

    save_multinodes_settings

    setup_traefik

    add_systemd_services

    get_model

    if [[ -f /.dockerenv ]]; then
        searchd --config /etc/piler/manticore.conf
    else
        systemctl start piler-search
    fi

    create_default_tenant

    get_the_licence

else  # centos
    install_prerequisites_centos
    install_onnx_lib

    start_mysql_centos

    install_piler_centos
    install_piler_ui

    setup_traefik

    add_systemd_services

    fix_piler_conf

    if [[ ! -f /.dockerenv ]]; then
        systemctl enable --now mariadb
        systemctl enable --now valkey
        systemctl enable --now piler-search
    else
        searchd --config /etc/piler/manticore.conf
    fi

    init_db

    save_node_type
    write_ui_config

    get_model

    save_multinodes_settings

    if pgrep firewalld >/dev/null 2>&1; then
        firewall-cmd --add-service=smtp --permanent
        firewall-cmd --add-service=https --permanent
        firewall-cmd --reload
    fi

    create_default_tenant

    get_the_licence

    centos_notes
fi

echo "Installation completed successfully!"
