Skip to content
cc-addaccount 2.65 KiB
Newer Older
# This file is part of CloudControl.
#
# CloudControl is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CloudControl is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with CloudControl.  If not, see <http://www.gnu.org/licenses/>.


'''
Script used to create an account on cc-server account directory.
'''

import os
from getpass import getpass
from pwd import getpwnam
from grp import getgrnam
from optparse import OptionParser
from cloudcontrol.server.conf import CCConf

DEFAULT_ACCOUNT_DIRECTORY = '/var/lib/cc-server/'
DEFAULT_ROLE = 'cli'
UMASK = 0o0177
CHOWN_USER = 'cc-server'
CHOWN_GROUP = 'cc-server'

if __name__ == '__main__':
    op = OptionParser(usage='%prog [options] login')
    op.add_option('-d', '--directory', default=DEFAULT_ACCOUNT_DIRECTORY,
                  help='account directory')
    op.add_option('-p', '--password', action='store_true',
                  help='ask for the password')
    op.add_option('-c', '--copy', default=None,
                  help='copy this already existing account')
    op.add_option('-r', '--role', default=None, choices=('cli', 'hv', 'host'),
                  help='specify the role (default %default)')

    options, args = op.parse_args()

    if len(args) != 1:
        op.error('a login must be provided')

    if options.role is not None and options.copy is not None:
        op.error('you can\'t specify a role for a copy')

    if options.role is None:
        role = DEFAULT_ROLE
    else:
        role = options.role

    conf = CCConf(options.directory)

    if options.password:
        password = getpass('Password: ')
        password_again = getpass('Password (again): ')
        if password != password_again:
            op.error('password mismatch')
        elif not password:
            op.error('no password provided')
    else:
        password = None

    os.umask(UMASK)

    if options.copy is None:
        conf.create_account(args[0], role, password)
    else:
        conf.copy_account(options.copy, args[0], password)

    # Chown the files:
    uid = getpwnam(CHOWN_USER).pw_uid
    gid = getgrnam(CHOWN_GROUP).gr_gid
    filename = os.path.join(options.directory, '%s.json' % args[0])
    os.chown(filename, uid, gid)