#!/usr/bin/env python

from stat import ST_GID
from os import listdir, stat
from os.path import join, basename, realpath
from subprocess import check_call, CalledProcessError

from IPython.ultraTB import FormattedTB
trace = FormattedTB(mode='Verbose', color_scheme='NoColor', call_pdb=0)

def get_gid(path):
    return str(stat(path)[ST_GID])

def replay_spool(spool, autocommit):
    # Install our gids.
    for gid in listdir(join(spool, 'gid_pool')):
        gid_cmd = ['/usr/sbin/groupadd', '-o', '-g', gid, gid]
        print 'adding group: %s' % ' '.join(gid_cmd)
        try:
            if autocommit:
                check_call(gid_cmd)
        except CalledProcessError, e:
            if e.returncode is not 9: # we don't care if the group already exists
                raise e

    # Pre-calculate a gid->bundle_id map.
    gid__bundle_id = {}
    bundle_id_dir = join(spool, 'bundle_id_to_gid')
    for bundle_id in listdir(bundle_id_dir):
        gid = basename(realpath(join(bundle_id_dir, bundle_id)))
        gid__bundle_id[gid] = bundle_id
    print 'gid-to-bundle_id map:\n%s' % gid__bundle_id

    # Install our users.
    for uid in listdir(join(spool, 'uid_pool')):
        home = join(spool, 'uid_to_home_dir', uid)
        gid  = get_gid(home)
        bundle_id = gid__bundle_id[gid]

        comment = '%s.%s' % (bundle_id, uid)
        uid_cmd = ['/usr/sbin/useradd', '-M', '-u', uid, '-g', gid,
                                        '-c', comment, '-d', home, uid]

        print 'adding user: %s' % ' '.join(uid_cmd)
        try:
            if autocommit:
                check_call(uid_cmd)
        except CalledProcessError, e:
            if e.returncode is not 9: # we don't care if the user already exists
                raise e

def main():
    replay_spool('/security/activities', True)

if __name__ == "__main__":
    main()

