#!/bin/sh
#
# Author: Michael Conrad <do5mc at aprs4r.org>
#

MAIL_USER=support
MAIL_DOMAIN=aprs4r.org

# set default file
[ -z "$APRS4R_DEFAULT" ] && APRS4R_DEFAULT=/etc/default/aprs4r

# set etc path
[ -z "$APRS4R_ETC" ] && APRS4R_ETC=/etc/aprs4r

# set log path 
[ -z "$APRS4R_LOG" ] && APRS4R_LOG=/var/log/aprs4r

APRS4R_TMP=/tmp
APRS4R_TIMESTAMP=`date '+%Y-%m-%d-%H-%M'`
APRS4R_CRASHREPORT=aprs4r-crashreport-$APRS4R_TIMESTAMP
APRS4R_CRASHREPORT_DIR=$APRS4R_TMP/$APRS4R_CRASHREPORT

echo ""
echo "APRS4R crash report script"
echo ""

echo "creating dir $APRS4R_CRASHREPORT_DIR"
mkdir -p $APRS4R_CRASHREPORT_DIR

echo ""
echo "saving log files (aprs4r-stdout.log, aprs4r-stderr.log, aprs4r-watchdog.log, aprs4r.log, aprs4r.err)"
# copy aprs4r default file (/etc/default/aprs4r)
[ -f $APRS4R_DEFAULT ] && cp $APRS4R_DEFAULT $APRS4R_CRASHREPORT_DIR

# copy aprs4r configuration files (/etc/aprs4r/*.yaml)
[ -d $APRS4R_ETC ] && cp $APRS4R_ETC/*.yaml $APRS4R_CRASHREPORT_DIR

# copy aprs4r stdout log file
[ -f $APRS4R_LOG/aprs4r-stdout.log ] && cp $APRS4R_LOG/aprs4r-stdout.log $APRS4R_CRASHREPORT_DIR

# copy aprs4r stderr log file
[ -f $APRS4R_LOG/aprs4r-stderr.log ] && cp $APRS4R_LOG/aprs4r-stderr.log $APRS4R_CRASHREPORT_DIR

# copy aprs4r watchdog log file 
[ -f $APRS4R_LOG/aprs4r-watchdog.log ] && cp $APRS4R_LOG/aprs4r-watchdog.log $APRS4R_CRASHREPORT_DIR

# copy aprs4r log4r log files
[ -f $APRS4R_LOG/aprs4r.log ] && cp $APRS4R_LOG/aprs4r.log* $APRS4R_CRASHREPORT_DIR

# copy aprs4r log4r err files
[ -f $APRS4R_LOG/aprs4r.err ] && cp $APRS4R_LOG/aprs4r.err* $APRS4R_CRASHREPORT_DIR

echo "saving system output (lsusb, dmesg, ruby)"
# save lsusb output
[ -x /usr/sbin/lsusb ] || [ -x /usr/bin/lsusb ] && lsusb > $APRS4R_CRASHREPORT_DIR/lsusb.out

# save dmesg output
[ -x /bin/dmesg ] && /bin/dmesg > $APRS4R_CRASHREPORT_DIR/dmesg.out

# save ruby output 
[ -x /usr/bin/ruby ] && /usr/bin/ruby -v > $APRS4R_CRASHREPORT_DIR/ruby.out
[ -x /usr/bin/ruby1.8 ] && /usr/bin/ruby1.8 -v > $APRS4R_CRASHREPORT_DIR/ruby1.8.out
[ -x /usr/bin/ruby1.9 ] && /usr/bin/ruby1.9 -v > $APRS4R_CRASHREPORT_DIR/ruby1.9.out

echo ""
echo "building archive $APRS4R_CRASHREPORT_DIR.tar.gz"
tar zcf $APRS4R_TMP/$APRS4R_CRASHREPORT.tar.gz -C $APRS4R_TMP $APRS4R_CRASHREPORT

echo "removing dir $APRS4R_CRASHREPORT_DIR"
rm -rf $APRS4R_CRASHREPORT_DIR

echo ""
echo "Please send crash report $APRS4R_CRASHREPORT_DIR.tar.gz to $MAIL_USER@$MAIL_DOMAIN"
echo "" 
