s4-python: add function to manipulate sites in python
[samba.git] / source4 / scripting / python / samba / sites.py
1 #!/usr/bin/env python
2 #
3 # python site manipulation code
4 # Copyright Matthieu Patou <mat@matws.net> 2011
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 """Manipulating sites."""
21
22 import ldb
23 from ldb import FLAG_MOD_ADD
24
25 def create_site(samdb, configDn, siteName):
26     ret = samdb.search(base=configDn, scope=ldb.SCOPE_SUBTREE,
27                     expression='(&(objectclass=Site)(cn=%s))' % siteName)
28     if len(ret) != 0:
29         raise Exception('A site with the name %s already exists' % siteName)
30
31     m = ldb.Message()
32     m.dn = ldb.Dn(samdb, "Cn=%s,CN=Sites,%s" % (siteName, str(configDn)))
33     m["objectclass"] = ldb.MessageElement("site", FLAG_MOD_ADD, "objectclass")
34
35     samdb.add(m)
36
37     m2 = ldb.Message()
38     m2.dn = ldb.Dn(samdb, "Cn=NTDS Site Settings,%s" % str(m.dn))
39     m2["objectclass"] = ldb.MessageElement("nTDSSiteSettings", FLAG_MOD_ADD, "objectclass")
40
41     samdb.add(m2)
42
43     m3 = ldb.Message()
44     m3.dn = ldb.Dn(samdb, "Cn=Servers,%s" % str(m.dn))
45     m3["objectclass"] = ldb.MessageElement("serversContainer", FLAG_MOD_ADD, "objectclass")
46
47     samdb.add(m3)
48
49     return True
50
51 def delete_site(samdb, configDn, siteName):
52
53     dnsite = ldb.Dn(samdb, "Cn=%s,CN=Sites,%s" % (siteName, str(configDn)))
54     dnserver = ldb.Dn(samdb, "Cn=Servers,%s" % str(dnsite))
55
56     ret = samdb.search(base=dnserver, scope=ldb.SCOPE_ONELEVEL,
57                     expression='(objectclass=server)')
58     if len(ret) != 0:
59         raise Exception('Site %s still has servers in it, move them before removal' % siteName)
60
61     samdb.delete(dnsite, ["tree_delete:0"])
62
63     return True