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

PRODUCT="NICE Monitoring"
STATE_DIR="/var/lib/nice-monitoring"
STATE_FILE="${STATE_DIR}/state/bootstrap-v1.done"
CREDENTIALS_FILE="${STATE_DIR}/credentials/initial-admin.txt"
SECRETS_FILE="/etc/nice-monitoring/secrets.env"
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"

log() {
    printf '[nice-monitoring-bootstrap] %s\n' "$*"
    command -v logger >/dev/null 2>&1 && logger -t nice-monitoring-bootstrap -- "$*" || :
}

die() {
    log "ERROR: $*"
    exit 1
}

on_error() {
    local rc=$?
    log "Bootstrap failed at line ${BASH_LINENO[0]} (rc=${rc})."
    exit "$rc"
}
trap on_error 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; 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/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"

# Zabbix 8 frontend runtime gate. NiceOS currently ships PHP 8.4, but do not
# assume extensions silently: fail the appliance bootstrap if its PHP build is
# missing a mandatory capability.
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);
    }
'

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

# Resolve PostgreSQL data directory from NiceOS config if it declares PGDATA.
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)"
    if [[ -n "${pgdata_from_cfg}" ]]; then
        PGDATA="${pgdata_from_cfg}"
    fi
fi

# Persistent secrets make bootstrap idempotent and allow safe retries.
if [[ ! -s "${SECRETS_FILE}" ]]; then
    DB_PASSWORD="$(openssl rand -hex 24)"
    ADMIN_PASSWORD="N!$(openssl rand -hex 18)Aa9"
    cat > "${SECRETS_FILE}" <<EOF
DB_PASSWORD=${DB_PASSWORD}
ADMIN_PASSWORD=${ADMIN_PASSWORD}
EOF
    chmod 0600 "${SECRETS_FILE}"
else
    # shellcheck disable=SC1090
    source "${SECRETS_FILE}"
fi

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

log "Initializing PostgreSQL 16 at ${PGDATA}"
install -d -m 0700 -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
    if "${PG_BIN}/pg_isready" -q -h 127.0.0.1 -p 5432; then
        break
    fi
    sleep 1
done
"${PG_BIN}/pg_isready" -q -h 127.0.0.1 -p 5432 || die "PostgreSQL did not become ready"

log "Creating/updating Zabbix database role"
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
    log "Importing frozen Zabbix schema, images and initial data"
    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

# Basic dynamic sizing. Conservative defaults first; later releases will expose
# a full appliance sizing profile in the control plane.
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. Local overrides belong in a later-numbered file.
DBHost=127.0.0.1
DBPort=5432
DBName=${ZBX_DB}
DBUser=${ZBX_DB_USER}
DBPassword=${DB_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'
# NICE Monitoring self-monitoring profile.
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 config is kept outside the package-owned UI tree and linked into it.
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 = 'НАЙС Мониторинг';
\$IMAGE_FORMAT_DEFAULT = IMAGE_FORMAT_PNG;
EOF
chown root:nginx "${WEB_CONFIG}"
chmod 0640 "${WEB_CONFIG}"
ln -sfn "${WEB_CONFIG}" "${WEB_CONFIG_LINK}"

# Generate appliance certificate. Self-signed is intentional for the first boot;
# later a user can replace it or use the control plane ACME/corporate-CA flow.
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"
    [[ -n "${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

if command -v php-fpm >/dev/null 2>&1; then
    php-fpm -t
fi
nginx -t

systemctl restart php-fpm.service
systemctl restart nginx.service

# Wait for the PHP frontend API.
api_url="https://127.0.0.1/api_jsonrpc.php"
for _ in $(seq 1 60); do
    if curl -ksS --max-time 2 -o /dev/null "${api_url}"; then
        break
    fi
    sleep 1
done

api_call() {
    local method="$1"
    local params="$2"
    local token="${3:-}"
    local -a headers=(-H 'Content-Type: application/json-rpc')
    if [[ -n "${token}" ]]; then
        headers+=(-H "Authorization: Bearer ${token}")
    fi
    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);
        $path=explode(".", $argv[1]);
        $v=$j;
        foreach ($path as $p) {
            if ($p === "") continue;
            if (!is_array($v) || !array_key_exists($p,$v)) exit(3);
            $v=$v[$p];
        }
        if (is_array($v)) echo json_encode($v);
        elseif (is_bool($v)) echo $v ? "1" : "0";
        else echo $v;
    ' "$expr"
}

log "Replacing upstream default Admin 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
else
    # Idempotent retry path: the password may already have been rotated before
    # a later step failed.
    login_json="$(api_call user.login \
        "{\"username\":\"Admin\",\"password\":\"${ADMIN_PASSWORD}\",\"userData\":true}")"
    admin_token="$(printf '%s' "${login_json}" | json_get result.sessionid)"
    admin_userid="$(printf '%s' "${login_json}" | json_get result.userid)"
fi

# Password rotation invalidates sessions. Log in with the appliance password.
login_json="$(api_call user.login \
    "{\"username\":\"Admin\",\"password\":\"${ADMIN_PASSWORD}\",\"userData\":true}")"
admin_token="$(printf '%s' "${login_json}" | json_get result.sessionid)"

# Stronger appliance-wide password policy.
api_call authentication.update \
    '{"passwd_min_length":12,"passwd_check_rules":15}' \
    "${admin_token}" >/dev/null || log "Warning: could not update password policy"

# Create a dedicated host group and self-monitoring host.
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);
    $r=$j["result"] ?? [];
    foreach ($r as $t) {
        if (($t["name"] ?? "") === "Linux by Zabbix agent active") {
            echo $t["templateid"]; exit;
        }
    }
    if (!empty($r[0]["templateid"])) echo $r[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
    if [[ -n "${template_id}" ]]; then
        templates="\"templates\":[{\"templateid\":\"${template_id}\"}],"
    else
        templates=""
        log "Warning: standard Linux template not found; self-host created without a template"
    fi
    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

# End API session where possible.
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}

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

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

# Web service is installed and configured, but its browser-backed reporting
# feature will be completed together with the reporting profile.
systemctl enable zabbix-web-service.service >/dev/null 2>&1 || :
systemctl start zabbix-web-service.service >/dev/null 2>&1 || :

printf "completed_at=%s\nversion=0.1.2-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 appliance bootstrap completed: https://${primary_ip}/"
