#include "strerr.h"
#include "buffer.h"
#include "cookie.h"
#include "now.h"
#include "fmt.h"
#include "scan.h"
#include "env.h"

#include "secret.h"

static const char* fatal = "sendok-create: fatal: ";

const char* prefix;
const char* suffix;
char secret[SECRET_MAX];
int secret_len;
datetime_sec expire;
const char* sender;

static void die_usage() {
  strerr_die2x(100,fatal,"usage: sendok-create expire prefix secret suffix");
}

static void die_out() {
  strerr_die2sys(111,fatal,"unable to write output");
}

static void doit() {
  char hash[COOKIE];
  char strnum[FMT_ULONG];
  unsigned long u;

  u = expire;
  strnum[fmt_ulong(strnum,u)] = 0;
  cookie(hash, secret, secret_len, strnum, sender, "");

  if(buffer_puts(buffer_1, prefix) < 0) die_out();
  if(buffer_puts(buffer_1, strnum) < 0) die_out();
  if(buffer_puts(buffer_1, ".") < 0) die_out();
  if(buffer_put(buffer_1, hash, COOKIE) < 0) die_out();
  if(buffer_puts(buffer_1, suffix) < 0) die_out();
  if(buffer_flush(buffer_1) < 0) die_out();
}

int main(int argc, char **argv) {
  const char* x;
  unsigned long u;

  argv++;

  sender = env_get("SENDER");
  if(!sender)
    strerr_die2x(100,fatal,"$SENDER is not set");

  x = *argv++;
  if(!x) die_usage();
  scan_ulong(x,&u);
  expire = now() + u;

  prefix = *argv++;
  if(!prefix) die_usage();

  x = *argv++;
  if(!x) die_usage();
  secret_len = secret_read(x, secret);
  if(secret_len < 0) strerr_die2sys(111,fatal,"unable to read secret: ");

  suffix = *argv++;
  if(!suffix) die_usage();

  doit();
  return 0;
}
