#!/bin/sh
OUTPUT_BASE_DIR="/tmp/system_dump"
SYSDB_OUTPUT_FNAME="${OUTPUT_BASE_DIR}/sysdb.txt"
SYSLOG_PATH="/var/log"
EVENTLOG_PATH="/data/log"
CONFIG_PATH="/data/ctm"
VOLATILE_CONFIG_PATH="/var/volatile/config"
DATE_SUFFIX=$(/bin/date "+%F-%H-%M-%S")
TAR_FNAME="/tmp/system_dump_${DATE_SUFFIX}.tgz"

init_folder()
{
	/bin/rm -rf ${OUTPUT_BASE_DIR}
	/bin/rm -rf ${OUTPUT_BASE_DIR}*.tgz
	/bin/mkdir -p ${OUTPUT_BASE_DIR}
}

get_sysdb()
{
	/bin/echo "Getting sysdb"
	/usr/bin/cmd sysdb get &> ${SYSDB_OUTPUT_FNAME}
}

get_logs()
{
	/bin/echo "Getting logs"
	/bin/cp ${SYSLOG_PATH}/syslog* ${OUTPUT_BASE_DIR}
	/bin/cp ${EVENTLOG_PATH}/eventlog* ${OUTPUT_BASE_DIR}
}

get_config()
{
	/bin/echo "Getting configs"
	/bin/cp ${CONFIG_PATH}/config.json ${OUTPUT_BASE_DIR}
	/bin/cp ${VOLATILE_CONFIG_PATH}/config.running ${OUTPUT_BASE_DIR}/config.running.json
}

add_pre_blocks()
{
	/bin/echo -e "<pre>\n$(cat $1)\n</pre>" > $1
}

get_dashboards()
{
	/bin/echo "Getting dashboards"
	/usr/bin/curl -o ${OUTPUT_BASE_DIR}/system_status.html http://localhost/cgi-bin/cmdsysdbpage.cgi?PAGE=SYSTEM_PAGE
	/usr/bin/curl -o ${OUTPUT_BASE_DIR}/cell_status.html http://localhost/cgi-bin/cmdsysdbpage.cgi?PAGE=CELL_PAGE
	/usr/bin/curl -o ${OUTPUT_BASE_DIR}/network_status.html http://localhost/cgi-bin/cmdnetwork.cgi
	/usr/bin/curl -o ${OUTPUT_BASE_DIR}/firewall_status.html http://localhost/cgi-bin/firewall.cgi
	/usr/bin/curl -o ${OUTPUT_BASE_DIR}/vpn_status.html http://localhost/cgi-bin/cmdipsec.cgi
	/usr/bin/curl -o ${OUTPUT_BASE_DIR}/can_dump.html http://localhost/cgi-bin/cmdcan.cgi
	# format raw response that needs to keep newlines
	add_pre_blocks ${OUTPUT_BASE_DIR}/firewall_status.html
	add_pre_blocks ${OUTPUT_BASE_DIR}/vpn_status.html
	add_pre_blocks ${OUTPUT_BASE_DIR}/can_dump.html
}

create_tar()
{
	/bin/echo "Generating tgz"
	/bin/tar -czf ${TAR_FNAME} -C ${OUTPUT_BASE_DIR} .
}

init_folder
get_sysdb
get_logs
get_config
get_dashboards
create_tar
/usr/bin/cmd filepush ${TAR_FNAME} log normal
