#!/usr/bin/env bash

role_preflight() {
    if [[ "${ZHCT_STATIC_VALIDATE:-0}" != "1" ]]; then
        require_command rpm
        require_command dnf
        require_command sha256sum
    fi
}

stage_emqx_templates() {
    ensure_dir "$TEMPLATE_ROOT" 0750 root root
    run rsync -a --delete "$ROLE_ROOT/templates/" "$TEMPLATE_ROOT/"
    install_file "$ROLE_ROOT/templates/runtime/provision-emqx-cookie.sh" /usr/local/sbin/provision-emqx-cookie.sh 0750 root root
    stop_disable_units "$UNITS_MANIFEST"
}

role_install() {
    if [[ "${ZHCT_STATIC_VALIDATE:-0}" == "1" ]]; then
        log 'STATIC: emqx install plan loaded'
        return
    fi
    install_offline_rpms
    if ! rpm -q emqx >/dev/null 2>&1; then
        run rpm -K "$(asset_path emqx-5.8.9-el8-amd64.rpm)"
        run dnf --disablerepo='*' install -y "$(asset_path emqx-5.8.9-el8-amd64.rpm)"
    fi
    stage_emqx_templates
}

role_verify() {
    if [[ "${ZHCT_STATIC_VALIDATE:-0}" == "1" ]]; then
        log 'STATIC: emqx role verification contract loaded'
        return
    fi
    rpm -q --qf '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' emqx | grep -Fq 'emqx-5.8.9-1.el8.x86_64'
    emqx version | grep -Fq '5.8.9'
    verify_template_units_inactive "$UNITS_MANIFEST"
}

role_seal() {
    run rm -f /etc/zhct/node.env
    run rm -rf /etc/zhct/secrets
    run rm -f /etc/emqx/emqx.conf
    run find /var/lib/emqx /var/log/emqx -mindepth 1 -delete
    run find /etc/emqx/certs -mindepth 1 -delete
    run rm -f /etc/emqx/acl.conf
}

role_post_clone() {
    local node_template="$TEMPLATE_ROOT/nodes/$NODE_KEY"
    require_dir "$node_template"
    install_file "$node_template/emqx.conf" /etc/emqx/emqx.conf 0600 emqx emqx
    stop_disable_units "$UNITS_MANIFEST"
}

role_activate() {
    if [[ "$DRY_RUN" == "1" ]]; then
        log 'DRY-RUN: would inject the EMQX cluster cookie, check config and activate this Core node'
        return
    fi
    require_command python3
    materialize_secret /etc/emqx/emqx.conf __EMQX_CLUSTER_COOKIE__ /etc/zhct/secrets/emqx.cluster-cookie
    grep -Eq '__[A-Z0-9_]+__' /etc/emqx/emqx.conf && die 'EMQX cookie placeholder has not been injected'
    emqx check_config
}

role_rollback() {
    stop_disable_units "$UNITS_MANIFEST"
}
