#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");
}

static int acct_uid;
static int acct_gid;
static int log_uid;
static int log_gid;

static const char *acct;
static const char *logacct;
static const char *dir;
static const char *servername;

int main(int argc, char **argv) {
  struct passwd *pw;

  argv++;

  acct = *argv++;
  if(!acct) die_usage();
  pw = getpwnam(acct);
  if(!pw)
    strerr_die3x(111, fatal,"unknown account ",acct);
  acct_uid = pw->pw_uid;
  acct_gid = pw->pw_gid;

  logacct = *argv++;
  if(!logacct) die_usage();
  pw = getpwnam(logacct);
  if(!pw)
    strerr_die3x(111, fatal,"unknown account ",logacct);
  log_uid = pw->pw_uid;
  log_gid = pw->pw_gid;

  dir = *argv++;
  if(!dir) die_usage();
  if(dir[0] != '/') die_usage();

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

  init(dir, fatal);
  makelog(logacct, log_uid, log_gid);

  makedir("env");
  perm(0755);
  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(0700);
  owner(acct_uid, acct_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;
}
