#!/bin/bash
set -euo pipefail
shopt -s nullglob

ROOT_DIR="$(cd "$(dirname "$(readlink "$0" || echo "$0")")"/..; pwd -P)"

echo "Running node dump in ${ROOT_DIR}"

cd "${ROOT_DIR}"

DUMP="log/node_dump_$(date +"%Y%m%d_%H%M%S").tar.gz"

collect() {
    echo "========================================================"
    echo "    $*"
    echo "========================================================"
    eval "$*" || echo "Unavailable"
    echo -e '\n'
}

{
    collect bin/emqx_ctl broker
    collect bin/emqx eval "'emqx_node_dump:sys_info()'"

    collect uname -a
    collect uptime
    collect free -h
    collect netstat -tnl

    collect bin/emqx_ctl plugins list
    collect bin/emqx_ctl modules list

    collect bin/emqx_ctl vm all
    collect bin/emqx_ctl listeners
} > log/sysinfo.txt

{
    collect bin/emqx eval "'emqx_node_dump:app_env_dump()'"
} > log/conf.dump

# Collect log files that are not older than 3 days:
LOGS=$(find log -mtime -3 \( -name '*.log.*' -or -name 'run_erl.log*' \))

tar czf "${DUMP}" ${LOGS} \
    log/sysinfo.txt \
    log/conf.dump

## Cleanup:
rm log/sysinfo.txt
#rm log/conf.dump # Keep it for inspection

echo "Created a node dump ${DUMP}"
echo -e "\nWARNING: this script tries to obfuscate secrets, but make sure to
inspect log/conf.dump file manually before uploading the node dump
to a public location."
