#include "strerr.h"
#include "cookie.h"
#include "now.h"
#include "scan.h"
#include "fmt.h"
#include "str.h"
#include "byte.h"
#include "env.h"

#include "secret.h"

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

char secret[SECRET_MAX];
int secret_len;
const char* sender;
const char* hash; 

static void die_usage() {
  strerr_die2x(100,fatal,"usage: sendok-check secret cookie");
}

static void die_trash() {
  strerr_die2x(100,fatal,"cookie doesn't check out");
}

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

  hash += scan_ulong(hash, &u);
  if(u < now()) die_trash();
  if(*hash++ != '.') die_trash();
  if(str_len(hash) != COOKIE) die_trash();

  strnum[fmt_ulong(strnum,u)] = 0;
  cookie(verify, secret, secret_len, strnum, sender, "");
  if(!byte_equal(hash,COOKIE,verify)) die_trash();
}

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

  argv++;

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

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

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

  doit();
  return 0;
}
