#! /usr/bin/python

#
# Hacky RANCID script for Netonix switches
# 
#

import subprocess
import sys, getopt, os
import time

# usage: wisprancid [-d] [-f filename] hostname
# Process arguments
opts, args = getopt.getopt(sys.argv[1:],"df:")

debug = False
filename = ""
backup_dir = "/tmp/"

for opt, arg in opts:
    if opt == '-d':
        debug = True
    elif opt == '-f':
        filename = arg
    else:
        print opt
        print arg

host = args[0]

# Get the switch to run a backup and copy to host
login_command = "wisplogin -b %s %s" % (backup_dir, host)
p = subprocess.Popen(login_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

# Now we're going to untar the file to a directory
expansion_path = "%s%s" % (backup_dir, host)
if not os.path.exists(expansion_path):
    os.makedirs(expansion_path)

expansion_command = "tar xvf %s%s_restore.tar -C %s" % (backup_dir, host, expansion_path)
p = subprocess.Popen(expansion_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)


# Read config file, do any processing, then output so it's compatible with rancid
conf_path = "%s/www/config.json" % (expansion_path)
conf = open(conf_path, "r")
output_path = "%s.new" % (host)
output = open(output_path, "w")

for line in conf:
    # Do any config mangling you want here
    
    output.write(line)


conf.close()
output.close()