/*!
 * main.c
 *
 * Copyright (c) 2015-2018, NADAL Jean-Baptiste. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA
 * 
 * @Author:  NADAL Jean-Baptiste
 * @Date: 30/04/2015
 *
 */

/*-------------------------------- INCLUDES ---------------------------------*/

#include <cstdio>
#include <unistd.h>

extern "C" {
#include <libubus.h>
}

#include "ubus-sprinkler-model.h"

#include "sprinklers.h"

/*--------------------------------- GLOBALS ---------------------------------*/



/*!  ----------------------------------------------------------------------------
 *  @fn setupUbus
 *
 *  @brief Setup the UBus Mechanism.
 */
extern "C" {
static struct ubus_context *setupUbus (void)
{
	ubus_context *theCtx;

	if (uloop_init () !=0) {

		fprintf (stderr, "Failed to init Uloop.\n");
		return NULL;
	}

	signal (SIGPIPE, SIG_IGN);

	theCtx = ubus_connect (NULL);

	if (!theCtx) {

		fprintf (stderr, "Failed to connect to ubus\n");
		return NULL;
	}
	
	ubus_add_uloop (theCtx);

	return theCtx;
}
} // SetupUbus.


/*!  ----------------------------------------------------------------------------
 *  @fn main
 *
 *  @brief Main function of Domo Daemon.
 */
int main (void)
{
	int theRet = 0;
	SprinkerModel theSprinklersModel;
	
	struct ubus_context *theCtx = NULL;

	if (setuid (0)) {
		
		perror ("setuid");
		return 1;
	}

	/* Setup the Ubus context. */
	theCtx = setupUbus ();
	if (theCtx == NULL) {

		return -1;
	}

	/* Setup the sprinklers. */
	theRet = sprinklers_setup ();
	if (theRet != 0) {
		
		fprintf (stderr, "Impossible to Setup the Sprinkers.\n");
		return theRet;
	}

	/* Add the UBus to the model exposed. */
	ubus_add_object (theCtx, &theSprinklersModel);
	
	/* Main Event Loop. */
	uloop_run ();

	ubus_free (theCtx);
	
	uloop_done ();

	return theRet;
}
