#!/usr/bin/python2

import os
import re
import sys
import logging
import logging.handlers
import subprocess

progname = os.path.basename(os.path.abspath(sys.argv[0]))

logger = logging.getLogger(progname)
logger.setLevel(logging.INFO)

#handler = logging.handlers.SysLogHandler(address='/dev/log')
handler = logging.FileHandler('/var/log/ipupdown-local.log')
handler.setFormatter(logging.Formatter(progname + '[%(process)d]: %(levelname)s: ' + '%(message)s'))

logger.addHandler(handler)

if not sys.argv[2].startswith('eth'):
    sys.exit(0)

regname = re.compile('^[0-9]+: ([^:]+): ')
regaddr = re.compile('^[ ]+inet[ ]([0-9.]+)/')

try:
    ifaddr = subprocess.Popen([ 'ip', 'addr', 'show' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    stout, sterr = ifaddr.communicate()

    addrs = []
    iface = None

    for ln in stout.splitlines():
        m1 = regname.match(ln)
        if m1:
            tmpstr = m1.group(1)
            if tmpstr.startswith('eth') or tmpstr == 'lo':
                iface = tmpstr
            continue

        if iface is None:
            continue

        m2 = regaddr.match(ln)
        if m2:
            addrs.append(m2.group(1) + '/32')

except Exception, e:
    logger.error('failure processing interfaces: %s' % str(e))
    sys.exit(1)

configname = '/etc/snort/home-network.conf'
configtemp = configname + '.new'

try:
    fh = open(configtemp, 'w')

    netstr = ','.join(addrs)

    if len(netstr) == 0:
        netstr = '127.0.0.1/32'

    fh.write('#### Auto-generated file from ' + sys.argv[0] + ' ####\n\n')
    fh.write('ipvar HOME_NET [' + netstr + ']\n')

    fh.close()

except Exception, e:
    logger.error('unable to open %s: %s' % (configtemp, str(e)))
    sys.exit(1)

try:
    os.rename(configtemp, configname)
except Exception, e:
    logger.error('unable to replace configuration file %s: %s' % (configname, str(e)))
    sys.exit(1)

try:
    pidpath = '/var/run/'
    pidlist = os.listdir(pidpath)

    for fn in pidlist:
        if not fn.startswith('snort_'):
            continue

        fh = open(os.path.join(pidpath, fn), 'r')
        data = fh.read().strip('\n ')
        fh.close()

        try:
            pid = int(data)
            os.kill(pid, signal.SIGHUP)
        except Exception, e:
            logger.warning('unable to send SIGHUP to %s: %s' % (data, str(e)))

except Exception, e:
    logger.error('unable to list pidfiles: %s' % str(e))
    sys.exit(1)
