#define _XOPEN_SOURCE
#include <postgres.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>


text *sqlcrypt(text *key, text *salt);
/*sql create function sqlcrypt(text,text) returns text as 'DESTLIB' language 'c'*/

char *crypt(const char *key, const char *salt);
int rand(void);
void srand(unsigned int seed);


text *sqlcrypt(text *key, text *salt)
{
  text *ret;
  char pass[] = "123456789";
  char s[] = "...";
  char salts[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
  int j,k;
  struct timeval tv;


  s[2]=0;
  bzero(pass,9);
  if ((VARSIZE(salt)-VARHDRSZ) < 2)
    {
    gettimeofday(&tv,0);
    srand((unsigned int)(tv.tv_usec));
    j=(rand() % 64);
    k=(rand() % 64);
    s[0]=salts[j];
    s[1]=salts[k];
	   
    }
  else
    {
    memcpy(s,VARDATA(salt),2);
    }
  ret = palloc(VARHDRSZ + 13);
  bzero(ret,VARHDRSZ + 13);
  VARSIZE(ret) = (VARHDRSZ + 13);
  if ((VARSIZE(key)-VARHDRSZ) < 8)
  {
  	memcpy(pass,VARDATA(key),VARSIZE(key)-VARHDRSZ);
  }
  else
  {
	  memcpy(pass,VARDATA(key),8) ;
  }

  memcpy(VARDATA(ret), crypt(pass,s),13); 

  return ret;
}
