#!/usr/bin/ensim-python
###
#
# Copyright (c) Ensim Corporation 2000, 2001   All Rights Reserved.
#
# This software is furnished under a license and may be used and copied
# only  in  accordance  with  the  terms  of such  license and with the
# inclusion of the above copyright notice. This software or any other
# copies thereof may not be provided or otherwise made available to any
# other person. No title to and ownership of the software is hereby
# transferred.
#
# The information in this software is subject to change without notice
# and  should  not be  construed  as  a commitment by Ensim Corporation.
# Ensim assumes no responsibility for the use or  reliability  of its
# software on equipment which is not supplied by Ensim.
#
# Exit codes (on failure error message goes to stderr):
#  0 - success
#  1 - failure
# 
# Boolean arguments on the command line are given as 0 or 1. All the
# command line arguments are encoded to avoid problems with escapes.
#
# All functions defined here either return an error message if an
# error occured and "" if everything went well or allways return a
# valid value, but exit (with code 1) printing an error message if an
# error occurs. This second type of functions have _e appended to
# their name. Functions are allowed to print results onto stdout, but
# errors are printed only in the main program.
#
# Script to edit all name based sites when an IP address or hostname
# change occurs
# --------------------------------------------------------------------------
# $Id: NBDetectchanges.py,v 1.6 2003/02/11 04:10:30 naris Exp $
# $Name:  $
# --------------------------------------------------------------------------
from vh3 import virthost
from vh3 import virtutil
import cmdlnpopen
import string
import sys
import ensimapplpath
import logging

import ensimapplpath
import be_vherrordisp

def edit_domain():
    ipinfo = ipChanged()
    status_list = []
    if ipinfo:
        err =  edit_namebased_ip_addr(ipinfo)

    glob_status = be_vherrordisp.CLIError.SUCCESS
    for domain in virthost.get_domain_list():
        status = be_vherrordisp.CLIError.SUCCESS
        configs,errs = virthost.get_configs_from_site(domain)
        status_list.extend(errs)
        status = virthost.cli_display_status_list(status_list)
        glob_status = max(status, glob_status)
        if status != be_vherrordisp.CLIError.ERROR:
             command = getCommand(configs['ipinfo'],domain)
             if command:
                 write_to_syslog("Editing site %s \n %s: start" % (domain, command))
                 output,err,ret=cmdlnpopen.cmd3(command)
                 logmsg = "Exit code: %s \n Stdout: %s \n Stderr: %s" % (str(ret), str(output), str(err))
                 write_to_syslog(logmsg)
                 write_to_syslog("Editing site %s: end" % domain)
                 glob_status =  max(ret, glob_status)
        else:
             write_to_syslog("NOT editing site %s: failed to read site configuration" % domain)
    if glob_status == be_vherrordisp.CLIError.ERROR:
        return 1
    return 0

def edit_namebased_ip_addr(ipinfo):
    oldip, newip = string.split(ipinfo)[1:3]
    file = virtutil.SafeFile()
    path = '/etc/virtualhosting/namebased_ip_addrs'
    
    try:
        file.open(path, 'r')
        lines = file.readlines()
        file.close()
        file.open(path, 'w')
        for line in lines:
            if line.strip() == oldip:
                file.write(newip + '\n')
            else:
                file.write(line)
        file.close()
        return 0
    except:
        tb = logging.get_traceback_str()
	write_to_syslog('Could not edit /etc/virtualhosting/namebased_ip_addr: %s' % tb)
	return 1

def getCommand(dict, domain):
   command="/usr/bin/ensim-python /usr/local/bin/EditVirtDomain %s" % domain
   return command

def write_to_syslog(message):
    try:
        logging.write_log("detectchanges: %s" % str(message))
    except:
	pass

# XXX bad... needs to use regular file read/parse
def ipChanged():
    ipchange_cmd = '/bin/egrep "^IP" /etc/detectchanges/configurationchanged 2>/dev/null'
    out,err,ret = cmdlnpopen.cmd3(ipchange_cmd)
    if out:
        return out[0]
    else:
        return ''

if __name__ == '__main__':
    status = edit_domain()
    sys.exit(status)

