#!/usr/bin/python3

import argparse
import os
import re
import subprocess
import sys

if os.geteuid() != 0:
    print("Super-user privileges are required to rename endpoints")
    sys.exit(1)

parser = argparse.ArgumentParser(description="Rename the Intelligent Endpoint")
parser.add_argument('name', type=str, help='The name to be applied')
args = parser.parse_args()

_HOSTNAME_RE = re.compile("^[-a-zA-Z0-9]{1,63}$")

hostname = args.name.strip()
if not _HOSTNAME_RE.match(hostname):
    print("Invalid hostname: compliance with RFC 1034 is required ({pattern})".format(
        pattern=_HOSTNAME_RE.pattern,
    ))
    sys.exit(1)

if subprocess.call(['rw']) != 0:
    print("Unable to make the system writeable for configuration updates")
    sys.exit(1)

try:
    old_hostname = subprocess.check_output(["hostname"]).strip().decode('utf-8')

    #/etc/hosts
    ########################################
    if os.path.isfile("/etc/hosts"):
        print("Updating hosts for resolution...")
        old_file = open("/etc/hosts", 'r').readlines()
        with open("/etc/hosts", 'w') as new_file:
            for line in old_file:
                tokens = line.split()
                if not tokens or tokens[0].startswith('#'): #blank or a comment; don't touch it
                    new_file.write(line)
                else:
                    for (i, t) in enumerate(tokens):
                        if t == old_hostname:
                            tokens[i] = hostname
                    new_file.write(' '.join(tokens) + '\n')

    #/etc/hostname
    ########################################
    if os.path.isfile("/etc/hostname"):
        print("Updating persistent hostname...")
        open("/etc/hostname", 'w').write(hostname + '\n')

    #Runtime hostname
    ########################################
    print("Updating runtime hostname...")
    subprocess.check_call(["hostname", hostname])

    #SSH key regeneration
    ########################################
    if os.path.isdir("/etc/ssh"):
        print("Updating SSH host keys...")
        for ssh_key in os.listdir("/etc/ssh"):
            if ssh_key.startswith("ssh_host_"):
                os.unlink(os.path.join("/etc/ssh", ssh_key))
        subprocess.check_call(["ssh-keygen", "-A"])

    #Syncing changes
    print("Flushing changes to disk...")
    subprocess.call(["sync"])

    #Done
    print("Not all running processes will recognise the new hostname until the system is rebooted")
finally:
    if subprocess.call(['ro']) != 0:
        print("Unable to restore the system to a read-only state; a reboot is recommended")
