#!/usr/bin/env python
import sys
import os
import pwd

argv = sys.argv[:]

if len(argv) < 2:
    sys.stderr.write("Usage: setuser USERNAME COMMAND [args..]\n")
    sys.exit(1)

if len(argv) < 3:
    argv.extend(["script", "-q", "/dev/null", "-c", "exec /bin/bash -il"])


def abort(message):
    sys.stderr.write("setuser: %s\n" % message)
    sys.exit(1)

username = argv[1]
try:
    user = pwd.getpwnam(username)
except KeyError:
    abort("user %s not found" % username)

try:
    os.initgroups(username, user.pw_gid)
    os.setgid(user.pw_gid)
    os.setuid(user.pw_uid)
    os.environ['USER'] = username
    os.environ['HOME'] = user.pw_dir
    os.environ['UID'] = str(user.pw_uid)

    os.chdir(os.environ['HOME'])
    os.execvp(argv[2], argv[2:])
except Exception as e:
    abort("cannot execute %s: %s" % (argv[2], str(e)))
