#!/usr/bin/env python
# vim: tabstop=4 softtabstop=4 shiftwidth=4 textwidth=80 smarttab expandtab

import sys
import glob
import re

hostname = sys.argv[1]

re_dhcp_hostname = re.compile('dhcp_hostname.*=', re.IGNORECASE)
re_dhcp_bootproto = re.compile('bootproto.*=.*dhcp', re.IGNORECASE)

for fname in glob.glob('/etc/sysconfig/network-scripts/ifcfg-*'):
    fix = False

    for line in open(fname).xreadlines():
        # If BOOTPROTO is DHCP we *may* want to fix it
        if re_dhcp_bootproto.search(line) is not None:
            fix = True

        # If DHCP_HOSTNAME is already set we *do not* want to fix it
        if re_dhcp_hostname.search(line) is not None:
            fix = False
            break

    # Fix the file if needed
    if fix:
        f = open(fname, "a")
        f.write("\nDHCP_HOSTNAME=\"%s\"\n" % (sys.argv[1]))
        print "Fixed file %s" % (fname)


