#!/bin/sh
#
# Save logs before rebooting/shutting down

TMPDIR=/tmp
SDDIR=/media/mmcblk0p1
LASTLOGSDIR=${SDDIR}/lastlogs

# How many log archives to keep
KEEPNUM=5

# Initialize file count - used for logrotate
FILECOUNT=0

stop() {
    if [ -d "$SDDIR" ]; then
        mkdir -p "$LASTLOGSDIR"

        # Count the number of files in the SD card logs directory
        FILES=$(find $LASTLOGSDIR -type f)
        for f in $FILES
        do
            FILECOUNT=$(( FILECOUNT+1 ))
        done
       
        # Manual log rotate - keep only 5 files
        if test $FILECOUNT -ge $KEEPNUM; then
            OLDPATH=$(pwd)
            cd $LASTLOGSDIR
            ls -1t . | tail -n +$KEEPNUM | xargs rm -f
            cd $OLDPATH
        fi

        # Prepare date string for file name
        DATEIS=$(date +"%a_%b_%d__%I_%M_%S_%p_%Z_%Y")
        FILENAME=log_$DATEIS.tgz

        # Compress /tmp and save to SD card
        cd $TMPDIR
        tar -c \
            --exclude=core \
            --exclude=reports \
            --exclude=goatyReports \
            --exclude=db_tmp \
            --exclude=tmp.* \
            --exclude=tmp_images \
            --exclude=node \
            --exclude=running \
            --exclude=rrti_lane* \
            --exclude=uploads \
            --exclude=avahi-daemon \
            --exclude=sd_mnt_tmp \
            --exclude=upgrade \
            --exclude=fpga \
            -zvf $FILENAME \
            .
        rsync -av $FILENAME $LASTLOGSDIR
        
        # Deleting file - useful when directly calling the script and not rebooting
        rm $FILENAME
    fi
}

restart() {
    stop
    start
}

case "$1" in
    start)
        ;;
    stop)
        stop
        ;;
    restart|reload)
        restart
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac

exit $?
