#!/bin/bash
set -e

function help {
	echo -en 'usage:\n' \
		'\tvcadebug packlogs [-m MESSAGE] [-o OUTDIR]\n' \
		'\t\t- make zip archive with various diagnostic info\n' \
		'\t\t  MESSAGE will be added to filenames if specified\n' \
		'\t\t  resulting log archive will be placed in OUTDIR when specified\n' \

}

function params_to_globals {
	OUTDIR="${OUTDIR-$(pwd)}" # default from env if set, pwd otherwise
	while [ $# -gt 0 ] ; do
		case "$1" in
			-m) MSG="${2}";;
			-o)
				OUTDIR="${2}"
				if [ "${OUTDIR:0:1}" != "/" ] ; then
					OUTDIR="$(pwd)/${2}"
				fi
			;;
			*)
				help
				exit 1
			;;
		esac
		shift; shift
	done

	FNAME_PREFIX=$(sed -r 's/[^a-zA-Z0-9]+/_/g' <<< "${MSG}${MSG:+_}$(hostname)")_$(date +%y%m%d_%H%M%S_)
}

# link $1 file if it exists; with name $2 if specified, otherwise orig filename
function link_file_if_exists {
	test -f "$1" && ln -s "$1" "${FNAME_PREFIX}${2-${1##*/}}"
}
# run $1 command (could have space separated args)
# save results in $2 if specified, otherwise $1 with spaces replaced by underscores
function save_command {
	{
		echo "--------- # $1 # ---------"
		eval "$1"
	} >> "${FNAME_PREFIX}${2-${1// /_}.log}"
}

function packlogs {
	workdir=$(mktemp -d)
	trap 'rm -rf "${workdir}"' EXIT
	cd "${workdir}"
	set +e # from now, errors are not crucial

	(
		link_file_if_exists '/var/log/vca_ifup_log' 'vca_ifup_2p0.log'
		link_file_if_exists '/var/log/vcactld' 'vcactld_2p0.log'
		link_file_if_exists '/var/log/vca/vcactld.log'
		link_file_if_exists '/var/log/vca/vca_ifup.log'
		link_file_if_exists '/var/log/vca/vcactl.log'
		link_file_if_exists '/var/log/vca/vcactl.log.old'
		link_file_if_exists '/etc/vca_config.d/vca_config.xml'
		link_file_if_exists '/etc/exports' 'exports.log'

		save_command 'dmesg'
		save_command 'ifconfig'
		save_command 'systemctl status vcactl'         'services.log'
		save_command 'systemctl status NetworkManager' 'services.log'
		save_command 'vcactl info system' 'info.log'
		save_command 'vcactl info hw'     'info.log'
		save_command 'vcactl info BIOS'   'info.log'
		save_command 'uname -a'    'version.log'
		if [ -f /etc/redhat-release ] ; then
			save_command 'cat /etc/redhat-release'       'version.log'
			save_command 'rpm -qa --pipe "grep -i vca"'  'version.log'
		elif [ -f /etc/debian_version ] ; then
			save_command 'lsb_release -a'		     'version.log'
			save_command 'dpkg -l | grep -i vca'         'version.log'
		fi

	) 2> "${FNAME_PREFIX}vcadebug_packlogs_errors.log"

	if [ -s "${FNAME_PREFIX}vcadebug_packlogs_errors.log" ] ; then
		cat "${FNAME_PREFIX}vcadebug_packlogs_errors.log"
	else
		rm  "${FNAME_PREFIX}vcadebug_packlogs_errors.log"
	fi

	zip "${OUTDIR}/vca_packedlogs_${FNAME_PREFIX%_}.zip" ./*
}


subcommand="${1}"
shift || true
params_to_globals "$@"

case "${subcommand}" in
	packlogs) packlogs;;
	*help|-h) help;;
	*)        help; exit 1;;
esac
