#!/usr/bin/python3
# publik-create-users
# 2018 Entr'ouvert

import subprocess

userlist = {
    'hobo': {'uid': '2100'},
    'authentic-multitenant': {'uid': '2101', 'home': '/var/lib/authentic2-multitenant'},
    'wcs': {'uid': '2102'},
    'passerelle': {'uid': '2104'},
    'combo': {'uid': '2105'},
    'fargo': {'uid': '2106'},
    'welco': {'uid': '2107'},
    'chrono': {'uid': '2108'},
    'bijoe': {'uid': '2110'},
    # do not use uid 2111 as it is old mandaye id
    # do not use uid 2112 as it is used for petale id in glc
    'lingo': {'uid': '2113'}
}


def run(cmd, check=True):
    # when dropping jessie and python3.4 support better use:
    # rr = subprocess.run(cmd, stdout=PIPE, shell=True, check=check)
    # return (rr.returncode, rr.stdout)
    try:
        output = subprocess.check_output(cmd, shell=True)
        return (0, output)
    except subprocess.CalledProcessError:
        if check:
            raise (Exception('Command failed: "{}"'.format(cmd)))
        else:
            return (1, None)


for user, data in userlist.items():
    uid = data.get('uid')
    home = data.get('home', '/var/lib/%s' % user)
    rc, ou = run('getent group {}'.format(user), check=False)
    if rc == 0:
        current_uid = ou.decode().split(':')[2]
        if current_uid != uid:
            raise (Exception('{} uid does not match'.format(user)))
    else:
        run('addgroup --system --gid {} {}'.format(uid, user))

    rc, ou = run('getent passwd {}'.format(user), check=False)
    if rc == 0:
        uid = ou.decode().split(':')[2]
        if uid != uid:
            raise (Exception('{} uid does not match'.format(user)))
    else:
        run(
            'adduser --disabled-password --system --uid {uid} --gecos "{user} daemon" --ingroup {user} --no-create-home --home {home} {user}'.format(
                user=user, uid=uid, home=home
            )
        )
