#! /usr/bin/python

"Set up cpanel cluster link"

import optparse
import os
import sys

def mkdir_p(dirname):
    parts=[]
    for bit in dirname.split("/"):
        parts.append(bit);
        part='/'.join(parts)
        if not part: continue
        if not os.path.exists(part):
            os.mkdir(part)
    pass

def nsplit(text,length):
    out=[]
    while text:
        out.append(text[:length])
        text=text[length:]
    return out

def cpanel_cluster_config(info):
    dirname='/var/cpanel/cluster/root/config' % info
    clusterinfofile='/var/cpanel/cluster/root/config/%(ip)s' % info
    dnsrole='/var/cpanel/cluster/root/config/%(ip)s-dnsrole' % info

    mkdir_p(dirname);
    info['whmauth_32'] = '\n'.join(nsplit(info['whmauth'],32));
    fd = open(clusterinfofile,'w');
    fd.write("""%(user)s\n%(ip)s\n%(whmauth_32)s\n""" % info)
    fd.close()
    os.chmod(clusterinfofile,0600)

    fd=open(dnsrole,'w')
    fd.write('sync')
    fd.close()

    print "SUCCESS: created "+clusterinfofile

if __name__=="__main__":
    parser=optparse.OptionParser("%prog [options] user ...")
    parser.add_option("--user",dest="user", action="store", default=None, help="cluster user")
    parser.add_option("--whmauth",dest="whmauth", action="store", default=None, help="cluster whmauth")
    parser.add_option("--ip",dest="ip", action="store", default=None, help="cluster ip")
    (options,args) = parser.parse_args()

    info={
        'ip': options.ip,
        'whmauth': options.whmauth,
        'user': options.user,
    }
    for k,v in info.items():
        if v: continue
        print "Option --"+k+" is mandatory"
        sys.exit(1)
    cpanel_cluster_config(info)
    sys.exit(0)

