#!/usr/bin/env bash
set -Eeuo pipefail
umask 077

STATE_DIR="/var/lib/nice-monitoring"
STATE_FILE="${STATE_DIR}/state/bootstrap-v2.done"
CREDENTIALS_FILE="${STATE_DIR}/credentials/initial-admin.txt"
SECRETS_FILE="/etc/nice-monitoring/secrets.env"
STORAGE_FILE="/etc/nice-monitoring/storage.conf"
TLS_DIR="/etc/nice-monitoring/tls"
WEB_CONFIG_DIR="/etc/zabbix/web"
WEB_CONFIG="${WEB_CONFIG_DIR}/zabbix.conf.php"
WEB_CONFIG_LINK="/usr/share/zabbix/ui/conf/zabbix.conf.php"

PG_BIN="/usr/pgsql/16/bin"
PGDATA_DEFAULT="/var/lib/pgsql/postgresql16"
PG_SERVICE="postgresql16.service"
ZBX_DB="zabbix"
ZBX_DB_USER="zabbix"

CLICKHOUSE_DB="zabbix"
CLICKHOUSE_USER="zabbix"
CLICKHOUSE_HTTP="http://127.0.0.1:8123"
CLICKHOUSE_SERVICE="clickhouse-server.service"
CLICKHOUSE_SQL_DIR="/usr/share/zabbix/sql-scripts/clickhouse"

log() {
    printf '[nice-monitoring-bootstrap] %s\n' "$*"
    command -v logger >/dev/null 2>&1 && logger -t nice-monitoring-bootstrap -- "$*" || :
}
die() { log "ERROR: $*"; exit 1; }
trap 'rc=$?; log "Bootstrap failed at line ${BASH_LINENO[0]} (rc=${rc})"; exit "$rc"' ERR

require_cmd() {
    command -v "$1" >/dev/null 2>&1 || die "Required command not found: $1"
}

for cmd in systemctl openssl curl php runuser hostname ip install awk sed grep date; do
    require_cmd "$cmd"
done

test -x "${PG_BIN}/initdb" || die "PostgreSQL 16 initdb not found"
test -x "${PG_BIN}/psql" || die "PostgreSQL 16 psql not found"
test -x "${PG_BIN}/pg_isready" || die "PostgreSQL 16 pg_isready not found"
test -x /usr/bin/clickhouse-client || die "clickhouse-client not installed"
test -x /usr/bin/clickhouse-server || die "clickhouse-server not installed"
test -x /usr/sbin/zabbix_server || die "zabbix_server not installed"
test -x /usr/sbin/zabbix_agent2 || die "zabbix_agent2 not installed"
test -d /usr/share/zabbix/ui || die "Zabbix frontend not installed"
test -x "${CLICKHOUSE_SQL_DIR}/history_all.sh" || die "Zabbix ClickHouse schema scripts not installed"

install -d -m0700 /etc/nice-monitoring "${TLS_DIR}"
install -d -m0750 "${STATE_DIR}" "${STATE_DIR}/state"
install -d -m0700 "${STATE_DIR}/credentials"
install -d -m0750 "${WEB_CONFIG_DIR}"
install -d -m0750 /etc/zabbix/zabbix_server.conf.d /etc/zabbix/zabbix_agent2.conf.d

# Frontend capability gate.
php -r '
    if (PHP_VERSION_ID < 80200 || PHP_VERSION_ID >= 80600) {
        fwrite(STDERR, "Unsupported PHP version: ".PHP_VERSION."\n");
        exit(10);
    }
    $required = ["pgsql","bcmath","mbstring","sockets","gd","xmlwriter","xmlreader","ctype","session"];
    $missing = [];
    foreach ($required as $ext) {
        if (!extension_loaded($ext)) $missing[] = $ext;
    }
    if ($missing) {
        fwrite(STDERR, "Missing required PHP extensions: ".implode(",", $missing)."\n");
        exit(11);
    }
'

CLICKHOUSE_HISTORY_TTL_DAYS=365
if [[ -r "${STORAGE_FILE}" ]]; then
    # shellcheck disable=SC1090
    source "${STORAGE_FILE}"
fi
[[ "${CLICKHOUSE_HISTORY_TTL_DAYS}" =~ ^[0-9]+$ ]] || die "Invalid ClickHouse TTL days"
(( CLICKHOUSE_HISTORY_TTL_DAYS >= 7 )) || die "ClickHouse TTL must be at least 7 days"
CLICKHOUSE_TTL_SECONDS=$((CLICKHOUSE_HISTORY_TTL_DAYS * 86400))

PGDATA="${PGDATA_DEFAULT}"
if [[ -r /etc/sysconfig/postgresql16.conf ]]; then
    pgdata_from_cfg="$(sed -nE 's/^[[:space:]]*PGDATA="?([^"]+)"?[[:space:]]*$/\1/p' /etc/sysconfig/postgresql16.conf | tail -n1 || true)"
    [[ -z "${pgdata_from_cfg}" ]] || PGDATA="${pgdata_from_cfg}"
fi

# Persistent secrets. Upgrade from 0.1.2 is supported: append ClickHouse secret
# when an older secrets.env already exists.
if [[ ! -s "${SECRETS_FILE}" ]]; then
    DB_PASSWORD="$(openssl rand -hex 24)"
    ADMIN_PASSWORD="N!$(openssl rand -hex 18)Aa9"
    CLICKHOUSE_PASSWORD="$(openssl rand -hex 24)"
    cat > "${SECRETS_FILE}" <<EOF
DB_PASSWORD=${DB_PASSWORD}
ADMIN_PASSWORD=${ADMIN_PASSWORD}
CLICKHOUSE_PASSWORD=${CLICKHOUSE_PASSWORD}
EOF
    chmod 0600 "${SECRETS_FILE}"
else
    # shellcheck disable=SC1090
    source "${SECRETS_FILE}"
    if [[ -z "${CLICKHOUSE_PASSWORD:-}" ]]; then
        CLICKHOUSE_PASSWORD="$(openssl rand -hex 24)"
        printf 'CLICKHOUSE_PASSWORD=%s\n' "${CLICKHOUSE_PASSWORD}" >> "${SECRETS_FILE}"
    fi
fi

[[ -n "${DB_PASSWORD:-}" ]] || die "DB_PASSWORD missing"
[[ -n "${ADMIN_PASSWORD:-}" ]] || die "ADMIN_PASSWORD missing"
[[ -n "${CLICKHOUSE_PASSWORD:-}" ]] || die "CLICKHOUSE_PASSWORD missing"

# ----------------------- PostgreSQL configuration DB -----------------------
log "Initializing PostgreSQL configuration/events database"
install -d -m0700 -o postgres -g postgres "${PGDATA}"

if [[ ! -s "${PGDATA}/PG_VERSION" ]]; then
    runuser -u postgres -- "${PG_BIN}/initdb" \
        -D "${PGDATA}" --encoding=UTF8 --locale=C \
        --auth-local=peer --auth-host=scram-sha-256
fi

systemctl enable "${PG_SERVICE}" >/dev/null
systemctl start "${PG_SERVICE}"

for _ in $(seq 1 60); do
    "${PG_BIN}/pg_isready" -q -h 127.0.0.1 -p 5432 && break
    sleep 1
done
"${PG_BIN}/pg_isready" -q -h 127.0.0.1 -p 5432 || die "PostgreSQL did not become ready"

if ! runuser -u postgres -- "${PG_BIN}/psql" -Atqc \
    "SELECT 1 FROM pg_roles WHERE rolname='${ZBX_DB_USER}'" | grep -qx 1; then
    runuser -u postgres -- "${PG_BIN}/psql" -v ON_ERROR_STOP=1 \
        -c "CREATE ROLE ${ZBX_DB_USER} LOGIN PASSWORD '${DB_PASSWORD}'"
else
    runuser -u postgres -- "${PG_BIN}/psql" -v ON_ERROR_STOP=1 \
        -c "ALTER ROLE ${ZBX_DB_USER} WITH LOGIN PASSWORD '${DB_PASSWORD}'"
fi

if ! runuser -u postgres -- "${PG_BIN}/psql" -Atqc \
    "SELECT 1 FROM pg_database WHERE datname='${ZBX_DB}'" | grep -qx 1; then
    runuser -u postgres -- "${PG_BIN}/createdb" -O "${ZBX_DB_USER}" "${ZBX_DB}"
fi

if ! PGPASSWORD="${DB_PASSWORD}" "${PG_BIN}/psql" -h 127.0.0.1 \
    -U "${ZBX_DB_USER}" -d "${ZBX_DB}" -Atqc \
    "SELECT to_regclass('public.dbversion')" | grep -qx dbversion; then
    for sql in schema.sql images.sql data.sql; do
        f="/usr/share/zabbix/sql-scripts/postgresql/${sql}"
        [[ -s "$f" ]] || die "Missing SQL file: $f"
        PGPASSWORD="${DB_PASSWORD}" "${PG_BIN}/psql" \
            -h 127.0.0.1 -U "${ZBX_DB_USER}" -d "${ZBX_DB}" \
            -v ON_ERROR_STOP=1 -f "$f"
    done
fi

# ------------------------- ClickHouse history DB ---------------------------
log "Initializing ClickHouse native Zabbix history provider"
systemctl enable "${CLICKHOUSE_SERVICE}" >/dev/null
systemctl start "${CLICKHOUSE_SERVICE}"

for _ in $(seq 1 90); do
    if curl -fsS --max-time 2 "${CLICKHOUSE_HTTP}/ping" | grep -q '^Ok'; then
        break
    fi
    sleep 1
done
curl -fsS --max-time 2 "${CLICKHOUSE_HTTP}/ping" | grep -q '^Ok' || \
    die "ClickHouse did not become ready"

# The server is bound to loopback by the storage package. The default local
# administrative user is used only to create/update the dedicated Zabbix role.
clickhouse-client --multiquery --query "
CREATE DATABASE IF NOT EXISTS ${CLICKHOUSE_DB};
CREATE USER IF NOT EXISTS ${CLICKHOUSE_USER}
    IDENTIFIED WITH sha256_password BY '${CLICKHOUSE_PASSWORD}';
ALTER USER ${CLICKHOUSE_USER}
    IDENTIFIED WITH sha256_password BY '${CLICKHOUSE_PASSWORD}';
GRANT CREATE, ALTER, DROP, INSERT, SELECT, UPDATE, OPTIMIZE
    ON ${CLICKHOUSE_DB}.* TO ${CLICKHOUSE_USER};
"

# IMPORTANT: upstream history_all.sh drops existing tables before creating
# them. Run it only for a new history database.
history_exists="$(clickhouse-client --query \
    "EXISTS TABLE ${CLICKHOUSE_DB}.history" | tr -d '[:space:]')"
if [[ "${history_exists}" != "1" ]]; then
    "${CLICKHOUSE_SQL_DIR}/history_all.sh" \
        --server "${CLICKHOUSE_HTTP}" \
        --db "${CLICKHOUSE_DB}" \
        --user "${CLICKHOUSE_USER}" \
        --password "${CLICKHOUSE_PASSWORD}" \
        --ttl "${CLICKHOUSE_TTL_SECONDS}"
fi

for table in history history_uint history_str history_log history_text history_json; do
    exists="$(clickhouse-client --user "${CLICKHOUSE_USER}" \
        --password "${CLICKHOUSE_PASSWORD}" \
        --query "EXISTS TABLE ${CLICKHOUSE_DB}.${table}" | tr -d '[:space:]')"
    [[ "${exists}" == "1" ]] || die "ClickHouse history table missing: ${table}"
done

# ----------------------------- Zabbix server -------------------------------
mem_kb="$(awk '/^MemTotal:/ {print $2}' /proc/meminfo)"
if (( mem_kb < 4 * 1024 * 1024 )); then
    CACHE_SIZE=64M; HISTORY_CACHE=32M; VALUE_CACHE=64M
elif (( mem_kb < 8 * 1024 * 1024 )); then
    CACHE_SIZE=128M; HISTORY_CACHE=64M; VALUE_CACHE=128M
else
    CACHE_SIZE=256M; HISTORY_CACHE=128M; VALUE_CACHE=256M
fi

cat > /etc/zabbix/zabbix_server.conf.d/90-nice-monitoring.conf <<EOF
# Managed by NICE Monitoring.
DBHost=127.0.0.1
DBPort=5432
DBName=${ZBX_DB}
DBUser=${ZBX_DB_USER}
DBPassword=${DB_PASSWORD}

# Zabbix 8 native ClickHouse history provider.
# Binary values are intentionally left on the default SQL provider because
# upstream ClickHouse history does not support history_bin.
HistoryProvider=clickhouse;value_types="uint,dbl,str,log,text,json",url=${CLICKHOUSE_HTTP},db=${CLICKHOUSE_DB},username=${CLICKHOUSE_USER},password=${CLICKHOUSE_PASSWORD}

CacheSize=${CACHE_SIZE}
HistoryCacheSize=${HISTORY_CACHE}
ValueCacheSize=${VALUE_CACHE}
StatsAllowedIP=127.0.0.1
EOF
chmod 0640 /etc/zabbix/zabbix_server.conf.d/90-nice-monitoring.conf
chown root:zabbix /etc/zabbix/zabbix_server.conf.d/90-nice-monitoring.conf

cat > /etc/zabbix/zabbix_agent2.conf.d/90-nice-monitoring-self.conf <<'EOF'
Server=127.0.0.1
ServerActive=127.0.0.1:10051
Hostname=nice-monitoring-server
HostMetadata=nice-monitoring,server,self
RefreshActiveChecks=60
EOF
chmod 0644 /etc/zabbix/zabbix_agent2.conf.d/90-nice-monitoring-self.conf

# ------------------------------- Frontend ----------------------------------
cat > "${WEB_CONFIG}" <<EOF
<?php
\$DB['TYPE'] = 'POSTGRESQL';
\$DB['SERVER'] = '127.0.0.1';
\$DB['PORT'] = '5432';
\$DB['DATABASE'] = '${ZBX_DB}';
\$DB['USER'] = '${ZBX_DB_USER}';
\$DB['PASSWORD'] = '${DB_PASSWORD}';
\$DB['SCHEMA'] = '';
\$DB['ENCRYPTION'] = false;

\$ZBX_SERVER = '127.0.0.1';
\$ZBX_SERVER_PORT = '10051';
\$ZBX_SERVER_NAME = 'НАЙС Мониторинг';

\$HISTORY_PROVIDERS[] = [
    'types' => ['uint','dbl','str','log','text','json'],
    'provider' => 'clickhouse',
    'url' => '${CLICKHOUSE_HTTP}',
    'db' => '${CLICKHOUSE_DB}',
    'username' => '${CLICKHOUSE_USER}',
    'password' => '${CLICKHOUSE_PASSWORD}'
];

\$IMAGE_FORMAT_DEFAULT = IMAGE_FORMAT_PNG;
EOF
chown root:nginx "${WEB_CONFIG}"
chmod 0640 "${WEB_CONFIG}"
ln -sfn "${WEB_CONFIG}" "${WEB_CONFIG_LINK}"

if [[ ! -s "${TLS_DIR}/server.key" || ! -s "${TLS_DIR}/server.crt" ]]; then
    host_name="$(hostname -f 2>/dev/null || hostname)"
    primary_ip="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '
        /src/ {for (i=1;i<=NF;i++) if ($i=="src") {print $(i+1); exit}}' || true)"
    san="DNS:${host_name},DNS:localhost,IP:127.0.0.1"
    [[ -z "${primary_ip}" ]] || san="${san},IP:${primary_ip}"
    openssl req -x509 -newkey rsa:3072 -sha256 -nodes -days 825 \
        -keyout "${TLS_DIR}/server.key" -out "${TLS_DIR}/server.crt" \
        -subj "/O=NICE SOFT GROUP/OU=NICE Monitoring/CN=${host_name}" \
        -addext "subjectAltName=${san}"
    chmod 0600 "${TLS_DIR}/server.key"
    chmod 0644 "${TLS_DIR}/server.crt"
fi

systemctl enable php-fpm.service nginx.service >/dev/null
command -v php-fpm >/dev/null 2>&1 && php-fpm -t
nginx -t
systemctl restart php-fpm.service
systemctl restart nginx.service

systemctl enable zabbix-server.service zabbix-agent2.service >/dev/null
systemctl restart zabbix-server.service
systemctl restart zabbix-agent2.service

# Wait for API after server/frontend restart.
api_url="https://127.0.0.1/api_jsonrpc.php"
for _ in $(seq 1 90); do
    curl -ksS --max-time 2 -o /dev/null "${api_url}" && break
    sleep 1
done

api_call() {
    local method="$1" params="$2" token="${3:-}"
    local -a headers=(-H 'Content-Type: application/json-rpc')
    [[ -z "${token}" ]] || headers+=(-H "Authorization: Bearer ${token}")
    curl -ksS --fail-with-body "${api_url}" "${headers[@]}" \
        --data "{\"jsonrpc\":\"2.0\",\"method\":\"${method}\",\"params\":${params},\"id\":1}"
}
json_get() {
    local expr="$1"
    php -r '
        $j=json_decode(stream_get_contents(STDIN), true);
        if (!is_array($j)) exit(2);
        $v=$j;
        foreach (explode(".", $argv[1]) as $p) {
            if ($p==="") continue;
            if (!is_array($v) || !array_key_exists($p,$v)) exit(3);
            $v=$v[$p];
        }
        echo is_array($v) ? json_encode($v) : $v;
    ' "$expr"
}

# Rotate upstream default Admin/zabbix once. On retries, use appliance password.
login_json="$(api_call user.login \
    '{"username":"Admin","password":"zabbix","userData":true}' || true)"
if admin_token="$(printf '%s' "${login_json}" | json_get result.sessionid 2>/dev/null)" &&
   admin_userid="$(printf '%s' "${login_json}" | json_get result.userid 2>/dev/null)"; then
    api_call user.update \
        "{\"userid\":\"${admin_userid}\",\"passwd\":\"${ADMIN_PASSWORD}\",\"current_passwd\":\"zabbix\"}" \
        "${admin_token}" >/dev/null
fi

login_json="$(api_call user.login \
    "{\"username\":\"Admin\",\"password\":\"${ADMIN_PASSWORD}\",\"userData\":true}")"
admin_token="$(printf '%s' "${login_json}" | json_get result.sessionid)"

api_call authentication.update \
    '{"passwd_min_length":12,"passwd_check_rules":15}' \
    "${admin_token}" >/dev/null || log "Warning: password policy update failed"

# Dedicated self-monitoring group.
group_json="$(api_call hostgroup.get \
    '{"output":["groupid","name"],"filter":{"name":["NICE Monitoring"]}}' "${admin_token}")"
group_id="$(printf '%s' "${group_json}" | php -r '
    $j=json_decode(stream_get_contents(STDIN),true);
    if (!empty($j["result"][0]["groupid"])) echo $j["result"][0]["groupid"];
')"
if [[ -z "${group_id}" ]]; then
    group_json="$(api_call hostgroup.create '{"name":"NICE Monitoring"}' "${admin_token}")"
    group_id="$(printf '%s' "${group_json}" | json_get result.groupids.0)"
fi

template_json="$(api_call template.get \
    '{"output":["templateid","name"],"filter":{"name":["Linux by Zabbix agent active","Linux by Zabbix agent"]}}' \
    "${admin_token}")"
template_id="$(printf '%s' "${template_json}" | php -r '
    $j=json_decode(stream_get_contents(STDIN),true);
    foreach (($j["result"] ?? []) as $t) {
        if (($t["name"] ?? "") === "Linux by Zabbix agent active") {
            echo $t["templateid"]; exit;
        }
    }
    if (!empty($j["result"][0]["templateid"])) echo $j["result"][0]["templateid"];
')"

host_json="$(api_call host.get \
    '{"output":["hostid"],"filter":{"host":["nice-monitoring-server"]}}' "${admin_token}")"
host_id="$(printf '%s' "${host_json}" | php -r '
    $j=json_decode(stream_get_contents(STDIN),true);
    if (!empty($j["result"][0]["hostid"])) echo $j["result"][0]["hostid"];
')"

if [[ -z "${host_id}" ]]; then
    templates=""
    [[ -z "${template_id}" ]] || templates="\"templates\":[{\"templateid\":\"${template_id}\"}],"
    api_call host.create \
        "{\"host\":\"nice-monitoring-server\",\"name\":\"NICE Monitoring Server\",${templates}\"interfaces\":[{\"type\":1,\"main\":1,\"useip\":1,\"ip\":\"127.0.0.1\",\"dns\":\"\",\"port\":\"10050\"}],\"groups\":[{\"groupid\":\"${group_id}\"}],\"tags\":[{\"tag\":\"NICE\",\"value\":\"Monitoring\"},{\"tag\":\"role\",\"value\":\"server\"}]}" \
        "${admin_token}" >/dev/null
fi
api_call user.logout '[]' "${admin_token}" >/dev/null 2>&1 || :

primary_ip="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '
    /src/ {for (i=1;i<=NF;i++) if ($i=="src") {print $(i+1); exit}}' || true)"
[[ -n "${primary_ip}" ]] || primary_ip="$(hostname -I 2>/dev/null | awk '{print $1}')"
[[ -n "${primary_ip}" ]] || primary_ip="127.0.0.1"

cat > "${CREDENTIALS_FILE}" <<EOF
НАЙС Мониторинг — первичный доступ

URL:      https://${primary_ip}/
Логин:    Admin
Пароль:   ${ADMIN_PASSWORD}

PostgreSQL хранит конфигурацию/события.
ClickHouse хранит историю uint/dbl/str/log/text/json.
Retention ClickHouse: ${CLICKHOUSE_HISTORY_TTL_DAYS} дней.

Сертификат первого запуска самоподписанный.
EOF
chmod 0600 "${CREDENTIALS_FILE}"

printf "completed_at=%s\nversion=0.1.3-dev1\n" "$(date -u +%FT%TZ)" > "${STATE_FILE}"
chmod 0600 "${STATE_FILE}"
systemctl start nice-monitoring-firstboot-banner.service >/dev/null 2>&1 || :

log "NICE Monitoring bootstrap completed with native ClickHouse history provider"
