#include "postgres.h"
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "fmgr.h"
#include "utils/timestamp.h"


#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif


PG_FUNCTION_INFO_V1(bacula_lstat_size);
PG_FUNCTION_INFO_V1(bacula_lstat_mtime);


/* forward declaration of actual conversion routine - see below */
static int from_base64(long *value, char *where);
#ifndef SECS_PER_YEAR
/* comes from Postgres in 8.2, but we need to define it in 8.0 */
static TimestampTz time_t_to_timestamptz(time_t tm);
#endif


/**
 * Get the file-size from the encoded stat structure.
 */
Datum 
bacula_lstat_size(PG_FUNCTION_ARGS)
{
   text     *t = PG_GETARG_TEXT_P(0);

   char* buf = alloca(VARSIZE(t)+1); 
   long value;
   int i,len = VARSIZE(t) - VARHDRSZ;
   memcpy(buf,VARDATA(t),len);
   buf[len] = 0;

   /* looking for st_size */   
   for (i=0;i<7;i++) {
      buf = strchr(buf,' ');
      if (buf==NULL) { buf = " "; }
      ++buf;
   }

   if (0 == from_base64(&value, buf))
      PG_RETURN_NULL();

   PG_RETURN_INT64( value );
}

/**
 * Get the modification-time from the encoded stat structure.
 */
Datum 
bacula_lstat_mtime(PG_FUNCTION_ARGS)
{
   text     *t = PG_GETARG_TEXT_P(0);
   long value;
   char* buf = alloca(VARSIZE(t)+1); 
   int i,len = VARSIZE(t) - VARHDRSZ;
   memcpy(buf,VARDATA(t),len);
   buf[len] = 0;

   /* looking for st_mtime */   
   for (i=0;i<11;i++) {
      buf = strchr(buf,' ');
      if (buf==NULL) { buf = " "; }
      ++buf;
   }

   if (0 == from_base64(&value,buf))
      PG_RETURN_NULL();

   TimestampTz ttz =  time_t_to_timestamptz(value);
#ifdef HAVE_INT64_TIMESTAMP
   PG_RETURN_INT64( ttz );
#else
   PG_RETURN_FLOAT8( ttz );
#endif
}


#ifndef SECS_PER_YEAR
#include "utils/datetime.h"
#define SECS_PER_DAY   86400
#define USECS_PER_SEC 1000000L
static TimestampTz 
time_t_to_timestamptz(time_t tm)
{
	TimestampTz result;

	result = (TimestampTz) tm -
		((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);

#ifdef HAVE_INT64_TIMESTAMP
	result *= USECS_PER_SEC;
#endif

	return result;
}
#endif

/*
  Following parts taken from Bacula;  original copyright:

   Bacula® - The Network Backup Solution

   Copyright (C) 2000-2007 Free Software Foundation Europe e.V.

   The main author of Bacula is Kern Sibbald, with contributions from
   many others, a complete list can be found in the file AUTHORS.
   This program is Free Software; you can redistribute it and/or
   modify it under the terms of version two of the GNU General Public
   License as published by the Free Software Foundation and included
   in the file LICENSE.

   This program 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
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
   02110-1301, USA.

   Bacula® is a registered trademark of John Walker.
   The licensor of Bacula is the Free Software Foundation Europe
   (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
   Switzerland, email:ftf@fsfeurope.org.
*/
/*
 *   Generic base 64 input and output routines
 *
 *    Written by Kern E. Sibbald, March MM.
 *
 *   Version $Id: base64.c 7272 2008-07-01 10:18:27Z kerns $
 */

static int const base64_digits[64] =
{
  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};

static int base64_inited = 0;
static uint8_t base64_map[128];

/* Initialize the Base 64 conversion routines */
static void
base64_init(void)
{
   int i;
   memset(base64_map, 0, sizeof(base64_map));
   for (i=0; i<64; i++)
      base64_map[(uint8_t)base64_digits[i]] = i;
   base64_inited = 1;
}


/*
 * Convert the Base 64 characters in where to
 * a value. No checking is done on the validity
 * of the characters!!
 *
 * Returns the number of characters processed.
 */
static int
from_base64(long *value, char *where)
{
   long val = 0;
   int i, neg;

   if (!base64_inited)
      base64_init();
   /* Check if it is negative */
   i = neg = 0;
   if (where[i] == '-') {
      i++;
      neg = 1;
   }
   /* Construct value */
   while (where[i] != 0 && where[i] != ' ') {
      val <<= 6;
      val += base64_map[(int) where[i++]];
   }

   *value = neg ? -val : val;
   return i;
}
