//-----------------------------------------------------------------------------
///
/// \brief  Biwak general functions
///
///         blablablub
///
/// \date   20121107
/// \author Maximilian Seesslen <mes@seesslen.net>
///
//-----------------------------------------------------------------------------


//---Includes------------------------------------------------------------------


//---Own------------------------------

#include <sys/types.h>        // pid_t
#include <biwak/rtc.hpp>      // getTime, getDate
#include <sys/time.h>         // _gettimeofday, timeval
#include <ctime>              // struct cm
#include <errno.h>            // EFAUL
#include <lepto/log.h>
#include <lepto/lepto.h>      // IS_ENABLED


//--- Forward declarations ----------------------------------------------------


#ifdef __cplusplus
extern "C"
{
#endif

void __aeabi_atexit();
pid_t getpid (void);
int kill(pid_t pid, int sig);
int settimeofday(const struct timeval *tv, const struct timezone *tz);
int gettimeofday (struct timeval *__restrict ptimeval,	  void *__restrict ptimezone);
void abort() __attribute__ (( used )); // "used" attribute actually helps here
int syscallsKeeper;

#ifdef __cplusplus
}
#endif


//---Implementation-----------------------------------------------------------


void __aeabi_atexit()
{
   return;
}

pid_t getpid (void)
{
   return(0);
}

int kill(pid_t pid, int sig)
{
   return(0);
}


// Linux: ptimezone is ignored, returned time is UTC
int gettimeofday ( struct timeval *__restrict ptimeval, void *__restrict ptimezone )
{
   ptimeval->tv_sec=12;
   ptimeval->tv_usec=0;
   if( libcBiwakRtc )
   {
      ptimeval->tv_sec = libcBiwakRtc->getSecondsSinceEpoch();
      return(0);
   }
   return(1);
}

int settimeofday(const struct timeval *tv, const struct timezone *tz)
{
   if( libcBiwakRtc )
   {
      struct tm  ts = *localtime(&tv->tv_sec);
      int sta1, sta2;

      // STM32F1xx: setTime does zero-out date
      sta2=libcBiwakRtc->setTime(ts.tm_hour, ts.tm_min, ts.tm_sec);
      sta1=libcBiwakRtc->setDate(ts.tm_year+1900, ts.tm_mon+1, ts.tm_mday);

      return( ( sta1 || sta2 ) ? EFAULT : 0 );
   };

   return(0);
}

void abort ()
{
   while(1)
   {
      //
   }
}

//---fin----------------------------------------------------------------------
