#!/usr/bin/env python
import os
import sys
import subprocess

if len(sys.argv) != 2:
    print ("usage: %s <hostname>" % sys.argv[0])
   
    sys.exit(2)

if os.geteuid() != 0:
    exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.")
    sys.exit(3)

hostname = None
try:
    hostname = sys.argv[1]
   
except:
    pass

if  hostname != "":
	oldhostnamepipe = os.popen("hostnamectl | grep Static | awk '{print $3}'")
	oldhostname = oldhostnamepipe.read()
	print(oldhostname)
	#read input file
	fin = open("/etc/hosts", "rt")
	#read file contents to string
	data = fin.read()
	#replace all occurrences of the required string
	data = data.replace(oldhostname, hostname+"\n")
	#close the input file
	fin.close()
	#open the input file in write mode
	fin = open("/etc/hosts", "wt")
	#overrite the input file with the resulting data
	fin.write(data)
	#close the file
	fin.close()
	data = hostname+"\n"
	with open('/etc/hostname', 'w+') as f:
		f.write(data)


