#include <pwd.h>

#include "strerr.h"
#include "auto_home.h"
#include "generic-conf.h"

const char* fatal = "passfd-conf: fatal: ";

static void die_usage(void) {
  strerr_die1x(100, 
      "passfd-conf: usage: passfd-conf acct logacct dir ip port sock");
}

char *acct;
char *logacct;
char *dir;
char *ip;
char *port;
char *sock;

struct passwd *pw;

int main(int argc, char **argv) {
  acct = argv[1];
  if(!acct) die_usage();
  logacct = argv[2];
  if(!logacct) die_usage();
  dir = argv[3];
  if(!dir) die_usage();
  if(dir[0] != '/') die_usage();
  ip = argv[4];
  if(!ip) die_usage();
  port = argv[5];
  if(!port) die_usage();
  sock = argv[6];
  if(!sock) die_usage();

  pw = getpwnam(logacct);
  if(!pw)
    strerr_die3x(111, fatal,"unknown account ",logacct);

  init(dir, fatal);
  makelog(logacct, pw->pw_uid, pw->pw_gid);

  makedir("env");
  perm(0755);
  start("env/ACCT"); outs(acct); outs("\n"); finish();
  perm(0644);
  start("env/IP"); outs(ip); outs("\n"); finish();
  perm(0644);
  start("env/PORT"); outs(port); outs("\n"); finish();
  perm(0644);
  start("env/SOCK"); outs(sock); outs("\n"); finish();
  perm(0644);

  start("run");
  outs("#!/bin/sh\n");
  outs("exec 2>&1\n");
  outs("exec envdir ./env \\\n");
  outs("sh -c '\n");
  outs("  exec \\\n");
  outs("  setuidgid $ACCT \\\n");
  outs("  tcpserver $IP $PORT \\\n");
  outs("  "); outs(auto_home); outs("/bin/passfd 0 $SOCK\n");
  outs("'\n");
  finish();
  perm(0755);

  return 0;
}
