#include <pwd.h>
#include "strerr.h"
#include "auto_home.h"
#include "generic-conf.h"

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

static void die_usage(void) {
  strerr_die1x(100,
      "tinyircd-conf: usage: tinyircd-conf acct logacct dir servername");
}

char *acct;
char *logacct;
char *dir;
char *servername;

struct passwd *pw_acct;
struct passwd *pw_logacct;

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();
  servername = argv[4];
  if(!servername) die_usage();

  pw_acct = getpwnam(acct);
  if(!pw_acct)
    strerr_die3x(111, fatal,"unknown account ",acct);
  pw_logacct = getpwnam(logacct);
  if(!pw_logacct)
    strerr_die3x(111, fatal,"unknown account ",logacct);

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

  makedir("env");
  perm(02755);
  start("env/ACCT"); outs(acct); outs("\n"); finish();
  perm(0644);
  start("env/INCOMING_SOCKET"); outs(dir); outs("/sock/incoming\n"); finish();
  perm(0644);
  start("env/SERVERNAME"); outs(servername); outs("\n"); finish();

  makedir("sock");
  perm(02700);
  owner(pw_acct->pw_uid, pw_acct->pw_gid);

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

  return 0;
}
