#!/usr/bin/python
#
# Copyright Skycloud Software 2019
#
# SkyForm AIP add local user on all AIP cluster nodes
#

import sys, os, yaml, sqlite3

startuid = 1000

hostlistfile = '/tmp/hostlist.txt'

if (len(sys.argv) < 2) or ((not sys.argv[1] == 'list') and (len(sys.argv) < 3)):
    print "Usage:", sys.argv[0], "add|del|list username [groupid]"
    sys.exit(1)

gid = ''

if (len(sys.argv) > 3):
    gid = ' -g ' + sys.argv[3]

username = ''
if not sys.argv[1] == 'list':
    if len(sys.argv[2]) > 8:
        print "The username too long, pleae use 8 character or less"
        sys.exit(1)

    if  not sys.argv[2][0].isalpha():
        print "The usename cannot start with a number"
        sys.exit(1)
    username = sys.argv[2]

if (not sys.argv[1] == 'add') and (not sys.argv[1] == 'del') and \
    (not sys.argv[1] == 'list'):
    print "The subcommand must be 'add' or 'del' or 'list'"
    sys.exit(1)

if not os.environ['CB_ENVDIR']:
    print "The AIP environment is not configured properly"
    sys.exit(1)

command = sys.argv[1]
aipenv = os.environ['CB_ENVDIR']
aipdatadir = os.path.dirname(aipenv) + '/work/data'

try:
    f = open(aipenv + "/cb.yaml", "r")
except:
    print "Cannot read cb.yaml. Please ensure AIP environment is set correctly"
    sys.exit(1)

aipConfStr = f.read()

aipConf = yaml.load(aipConfStr)
f.close()

hosts = ''
for host in aipConf['cluster']['hosts']:
    if not host['name'] == 'default':
#        if hosts == '':
#            hosts = host['name']
#        else:
#            hosts = hosts + ' ' +host['name']
        hosts = hosts + host['name'] + "\n"
f = open(hostlistfile, "w")
f.write(hosts)
f.close()

sqlfile = aipdatadir + '/users.db'
conn = sqlite3.connect(sqlfile)
c = conn.cursor()
c.execute('create table if not exists users(username char(8),id int)')
if command == 'add':
    c.execute('select * from users')
    users = c.fetchall()
    uid = -1
    if len(users) == 0:
        uid = startuid
    else:
        uids = []
        for user in users:
            if user[0] == username:
                print "Username", username, "exists with id", user[1]
                conn.close()
                sys.exit(1)
            uids.append(user[1])
        uids.sort()
        missingUids = [x for x in range(startuid, uids[-1]) if not x in uids]
        if len(missingUids) == 0:
            uid = uids[-1] + 1
        else:
            uid = missingUids[0]
    c.execute('insert into users (username, id) values ("' + username +
              '",' + str(uid) + ')')
    print "User",username,"with ID",uid,"Added"
    cmd = "ctask -u " + hostlistfile + " useradd -u " + str(uid) + gid + " " + username
    os.system(cmd)
#    print "To run:", cmd

if command == 'del':
    c.execute('select * from users where username = "' + username + '"')
    if c.fetchone() == None:
        print "User",username,"not found"
        conn.close()
        sys.exit(1)
    c.execute('delete from users where username = "' + username + '"')
    print "User",username,"deleted"
    cmd = "ctask -u " + hostlistfile + " userdel " + username
    os.system(cmd)
#    print "To run:", cmd
if command == 'list':
    c.execute('select * from users')
    users = c.fetchall()
    for user in users:
        print user[0],user[1]

conn.commit()
conn.close()
