#!/opt/maint/venv/bin/python3
"""Script to rotate the main IP of the server based on usage"""
# Vanessa V 8/24/12
from pathlib import Path
import sys
import shutil
from operator import itemgetter
import rads

IP_FILE = Path('/var/cpanel/mainips/root')
TEMP_FILE = Path('/var/cpanel/mainips/.root')


def main():
    try:
        with open(IP_FILE, encoding='utf-8') as file:
            ip_usage = {x: 0 for x in file.read().split()}
    except FileNotFoundError:
        sys.exit("No support for multiple main IPs...skipping")

    # Now get each user's IP
    for user in rads.all_cpusers():
        with open(Path('/var/cpanel/users', user), encoding='utf-8') as file:
            for line in file:
                if not line.startswith('IP='):
                    continue
                ip_address = line.split('=', maxsplit=1)[1].strip()
                # Update the array (increment the IP's counter by 1)
                if ip_address in ip_usage:
                    ip_usage[ip_address] += 1
                break

    # Sort the ip_usage dict by value, putting the least-used IPs first
    order_by_usage = sorted(list(ip_usage.items()), key=itemgetter(1))

    with open(TEMP_FILE, 'w', encoding='utf-8') as file:
        for ipaddr, _ in order_by_usage:
            file.write(f"{ipaddr}\n")

    TEMP_FILE.rename(IP_FILE)
    shutil.copyfile(IP_FILE, "/var/cpanel/mainips/tier2s")
    if rads.IMH_CLASS == 'hub':
        shutil.copyfile(IP_FILE, "/var/cpanel/mainips/hubhost")
    else:
        shutil.copyfile(IP_FILE, "/var/cpanel/mainips/inmotion")


if __name__ == "__main__":
    main()
