#include <unistd.h>
#include "str_defs.h"
#include "fmt_defs.h"
#include "vhangup_defs.h"

struct xx { char *a,*b,*c; };
char buf[8192], *p = buf;
unsigned char opt_len[512];

#define s(X) p += str_copy(p, X)
#define f(X) p += fmt_ulong(p, X)
#define sfs(a,b,c) s(a); f(b); s(c)

#define X(a,b,c) {#a,#b,#c}

struct xx o[] = {
  X(pri,nt,=),
  X(cl,ear,=),
  X(all,ow,=),
  X(de,ny,=),
  X(env,iron,=),
  X(new,line,=),
  X(sh,-A,=),
  X(sh,-B,=),
  X(t,z,=),
  X(day,s,=),
  X(month,s,=),
  X(ni,ce,=),
  X(ch,dir,=),
  X(de,lay,=),
  X(ch,root,=),
  X(time,out,=),
  X(issue,-file,=),
  X(login,-buffer,=),
  X(login,-prog,=),
  X(login,-argv,=),
  X(login,-prompt,=),
  X(noclear,-first,=),
  X(autologin,-name,=),
  X(autologin,-first,=),

  X(de,bu,g),
  X(echo,-o,ff),
#ifdef HAVE_SYSTEM_VHANGUP
  X(no,han,gup),
#endif
  X(no,user,name),
  X(date,-str,ing),
  X(long,-host,name),
  {0,0,0}
};

int main() {
  struct xx *x = o;
  int n,k, o_len;

  s("/* this file is auto generated.  do not edit! */\n\n"
    "#ifndef NGETTY_opts_defs_h\n"
    "#define NGETTY_opts_defs_h\n\n");
#ifdef HAVE_SYSTEM_VHANGUP
    s("#define HAVE_SYSTEM_VHANGUP\n\n");
#endif

  for (o_len=0, n=0, k=0, x=o; x->a; x++, n++) {
    char *t = x->b;
    int m = str_len(x->a) + str_len(x->b);

    if (*t=='-') t++;
    s("#define O"); s(x->a); s(t);

    if (x->c[0] != '=') { s(x->c); m += str_len(x->c); }
    else k++;

    opt_len[n] = m;
    o_len += m;
    sfs("\t", n, "\n"); 
  }

  sfs("\n#define MAX_equal\t", k, "\n");
  sfs("#define MAX_options\t", n, "\n");
  s("\nstatic char *o[MAX_options];\n"
    "extern char ** Oo;\n\n");

  sfs("const char P_opt[", o_len, "] = {\n");
  for (x=o,n=0; x->a; x++, n++) {
    char *t = "\"\t/* =";
    s("\t\""), s(x->a); s(x->b);
    if (x->c[0] != '=') { s(x->c); t = "\"\t/* "; }
    sfs(t, n, " */\n");
  }  
  s("};\n\n");
  
  s("const unsigned char P_len[MAX_options] = {\n");
  for (k=0; k<n; k++) {
    sfs("\t/* ", k, " */ ");
    sfs(" ", opt_len[k], ",\n");
  }

  p -= 2;
  s("\n};\n\n");
  s("#endif\n\n");

  n = p-buf;
  if (n != write(1, buf, n)) return 1;
  return 0;
}
