#!/bin/bash
#
# License: Copyright 2016 SpinetiX. This file is licensed
#          under the terms of the GNU General Public License version 2.
#          This program is licensed "as is" without any warranty of any
#          kind, whether express or implied.
#
### BEGIN INIT INFO
# Required-Start:
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 5
# Default-Stop:
# Short-Description: Saves bootlogs after firmware update
# Description: Saves bootlogs after firmware update
### END INIT INFO
# NOTE: this should be started at the end of boot.

# Init script information
NAME=updater-bootlog
DESC="save bootlog after update"

# The flag file
FLAG_FILE=/var/lib/updater/keep-bootlog

# The boot log
BOOTLOG=/var/log/boot

# The saved log file
SAVEDLOG=/var/log/updater/boot

# The highest backup of saved logs to keep
MAXKEEP=7

# Source the init script functions
. /etc/init.d/functions

start() {
    local RET
    local n p

    [ ! -e $FLAG_FILE ] && return

    echo -n "Starting $DESC: "

    if [ ! -e $BOOTLOG ]; then
	rm -f $FLAG_FILE
	echo -n "no bootlog to save "
	failure; echo
	return 1
    fi

    RET=0
    n=$MAXKEEP
    while [ $n -gt 1 ]; do
	let p=n-1
	if [ -e $SAVEDLOG.$p ]; then
	    mv -f $SAVEDLOG.$p $SAVEDLOG.$n || RET=1
	fi
	let n-=1
    done
    if [ -e $SAVEDLOG ]; then
	mv -f $SAVEDLOG $SAVEDLOG.1 || RET=1
    fi
    cp $BOOTLOG $SAVEDLOG || RET=1
    rm -f $FLAG_FILE || RET=1
    if type fsync >/dev/null 2>/dev/null ; then
	fsync $SAVEDLOG ${SAVEDLOG%/*} ${FLAG_FILE%/*} || RET=1
    else
	sync
    fi

    if [ $RET -eq 0 ]; then
	success; echo
    else
	failure; echo
	return 1
    fi

    return 0
}

parse() {
    case "$1" in
	start)
	    start
	    return $?
	    ;;
	stop)
	    return
	    ;;
	restart|condrestart)
	    return
	    ;;
	*)
	    echo "Usage: $NAME {start}" >&2
	    ;;
    esac

    return 1
}

parse $@
