#!/opt/imh-python/bin/python3 import argparse import sys import subprocess import os import pymysql API_PATH = "/scripts/cwp_api" def change_primary_domain(username, newdomain): root_cwp = pymysql.connect( read_default_file='/root/.my.cnf', database="root_cwp" ) cur = root_cwp.cursor(pymysql.cursors.DictCursor) # Sanity checks cur.execute('SELECT * FROM user WHERE username=%s', username) result = cur.fetchall() if len(result) == 0: print("User not found!") sys.exit(2) if len(result) > 1: print("Multipe records for user found!") sys.exit(3) olddomain = result[0]['domain'] # Update domain in mysql cur.execute( 'UPDATE user SET domain=%s WHERE id=%s', (newdomain, result[0]['id']) ) root_cwp.commit() # Rebuild and reload services apicmds = [f"{API_PATH} webservers rebuild_all", f"{API_PATH} webservers reload", f"hostnamectl set-hostname {newdomain}"] if os.path.isfile(f"/var/named/{olddomain}.db"): os.rename(f"/var/named/{olddomain}.db", f"/var/named/{newdomain}.db") elif os.path.isfile(f"/var/named/{newdomain}.db"): print( f"No zone found for {olddomain},", f"a zone already exists for {newdomain}", ) else: print( f"No zone found for {olddomain} or {newdomain},", "generating a new zone", ) apicmds.extend([f"account rebuild_var_named {username} {newdomain}"]) for apicmd in apicmds: print(f"Running {apicmd}") subprocess.run(apicmd.split(), check=False) subprocess.run(["/opt/imh-cwp-dns/update_zone", newdomain], check=False) # Update mail dirs if os.path.isdir(f"/var/vmail/{olddomain}"): if not os.path.isdir(f"/var/vmail/{newdomain}"): print(f"Maildir for {newdomain} found, moving") os.rename(f"/var/vmail/{olddomain}", f"/var/vmail/{newdomain}") else: print( f"Target mail dir /var/vmail/{newdomain} already exists!", "Please check the mail dirs in /var/vmail", ) else: print(f"No maildir for {olddomain} found, not moving") sys.exit(0) parser = argparse.ArgumentParser(description="Change CWP Primary Domain") parser.add_argument("username", type=str, help="Username to change domain for") parser.add_argument("newdomain", type=str, help="New Primary Domain") args = parser.parse_args() change_primary_domain(args.username, args.newdomain)