#!/usr/bin/python
# OpenChange provision script
#
# Copyright (C) Javier Amor Garcia <jamor@zentyal.com> 2015
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import optparse
import sys

# To allow running from the source directory
sys.path.append("python")

import samba.getopt as options
import openchange.provision as provision

parser = optparse.OptionParser("openchange_group [options] <groupname>")

sambaopts = options.SambaOptions(parser)
parser.add_option_group(sambaopts)

credopts = options.CredentialsOptions(parser)
parser.add_option_group(credopts)
parser.add_option("--firstorg", type="string", metavar="FIRSTORG",
                  help="select the OpenChange Organization Name")
parser.add_option("--firstou", type="string", metavar="FIRSTOU",
                  help="select the OpenChange Administration Group")
parser.add_option("--create", action="store_true", metavar="CREATE",
                  help="Create the OpenChange group account")
parser.add_option("--delete", action="store_true", metavar="DISABLE",
                  help="Delete OpenChange attributes for group")
parser.add_option("--update", action="store_true", metavar="DISABLE",
                  help="Update OpenChange attributes for group after switching between ditribution and security group")
parser.add_option("--mail", type="string", metavar="MAIL",
                  help="Group email address. If not specified, the email "
                       "will be samaccountname@realm")
opts, args = parser.parse_args()

if len(args) != 1:
    parser.print_usage()
    sys.exit(1)

action_options = filter(lambda(x): x, [opts.create, opts.delete, opts.update])
if len(action_options) == 0:
    parser.error("missing action option: --create, --delete and --update")
elif len(action_options) > 1:
    parser.error("--create, delete and update options are incompatible")

groupname = args[0]
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp)
provisionnames = provision.guess_names_from_smbconf(
    lp, creds, opts.firstorg, opts.firstou)

if opts.create:
    provision.newgroup(provisionnames, lp, creds, groupname, mail=opts.mail)
elif opts.delete:
    provision.delete_group(provisionnames, lp, creds, groupname)
elif opts.update:
    provision.update_group(provisionnames, lp, creds, groupname)
