#include <limits.h>
#include <sys/types.h>
#include <unistd.h>

#include "log.h"
#include "pathexec.h"
#include "strerr.h"
#include "user.h"
#include "fmt.h"
#include "prot.h"
#include "join.h"

static const char fatal[] = "tinysu: fatal: ";

static void die_usage() {
  strerr_die1x(100, "tinysu: usage: tinysu cmd [args]");
}

int main(int argc, const char * const *argv) {
  unsigned uid;
  static char userbuf[128];
  static char dirbuf[PATH_MAX];
  static char cmdbuf[1024];

  argv++;
  argc--;
  if(!*argv) die_usage();

  uid = getuid();
  if(user_fromuid(getuid(), userbuf, sizeof userbuf) < 0) {
    userbuf[fmt_ulong(userbuf, uid)] = '\0';
  }

  join(cmdbuf, sizeof cmdbuf, " ", argv, argc);

  if(!getcwd(dirbuf, sizeof dirbuf))
    strerr_die2sys(111,fatal,"unable to get cwd");

  log_identity("tinysu");
  log_str6("user=",userbuf,"; cwd=",dirbuf,"; cmd=",cmdbuf);

  prot_uid(geteuid());

  pathexec(argv);
  strerr_die2sys(111, fatal, "unable to execute child: ");
  /* not reached */
  return 100;
}
