#!/bin/sh /etc/rc.common
# Copyright (C) 2007-2014 OpenWrt.org

START=93
STOP=45

USE_PROCD=1

PROG=/usr/bin/weathermon
NICEPRIO=-1

BACKUP_DIR=`uci get weathermon.process.backup_dir`
BACKLOGDB=`uci get weathermon.process.backlogdb` 
LOGDB=`uci get weathermon.process.logdb` 
WORK_DIR=`uci get weathermon.process.working_dir`

start_service() {

	mkdir -p "$WORK_DIR"

	if [ ! -z "$BACKLOGDB" ]; then

		sqlite3 $BACKLOGDB "select * from queue limit 1" > /dev/null
        
        	if [ "$?" != "0" ]; then
	 		BACKLOG_BASE=$(basename "$BACKLOGDB")
 			cp "$BACKUP_DIR/$BACKLOG_BASE" "$BACKLOGDB"
 		fi
 			
 	fi

	if [ ! -z "$LOGDB" ]; then
	
	        sqlite3 $LOGDB "select * from log limit 1" > /dev/null
        
	        if [ "$?" != "0" ]; then
 			LOG_BASE=$(basename "$LOGDB")
 			cp "$BACKUP_DIR/$LOG_BASE" "$LOGDB"
 		fi

 	fi

        procd_open_instance
        procd_set_param command "$PROG"
        procd_set_param nice "$NICEPRIO"
        procd_set_param respawn
        procd_close_instance
}

stop_service() {
	killall weathermon
	killall weathermon-iio
	/usr/bin/weather-backup
}