#!/usr/bin/env python
#
print("""
################################################################################
# The goal of this program is to pull F5 running configuration one at a time.
# Then print out the interesting object definition for you.
#
################################################################################
# Version: 0.2, Date: September 24 2018
# Author: Sam Li 
# Usage:
#         $ f5-search  abc
###############################################################################
# Prerequisite:
# a. F5 remote SSH access service are setup.
# b. You have privileged access to the F5 TMOS configuration.
###############################################################################
""")
import f5_admin
from f5_admin.util import *
import os
import sys
# using multiprocessing to speed up the search: https://docs.python.org/2/library/multiprocessing.html
from multiprocessing import Pool, TimeoutError

#  Help message
def print_help():
    print("Program to search known F5 nodes one by one for the specific sting match. ")
    print("Usage: ")
    print("$ f5-search abc")

# worker function to do the dirty work
def search_node(node):
    with f5_admin.F5Client(credential, 7, False) as my_f5:
        my_f5.load(node)
        my_objs = my_f5.filter_f5_objs(my_f5.top_objs, sys.argv[1])
        if len(my_objs) > 0:
            return {node: my_objs}
        else:
            return None

################################################################################
#      Main Program
################################################################################
if __name__ == '__main__':
    #print "Command argv len: ", sys.argv, len(sys.argv)
    # simple command argument check
    if len(sys.argv) != 2:
        print_help()
        exit(1)

    # Step 1: default F5 connection string
    credential = {
        "user_name": "root",
        "user_pass": ""
    }
    # start 8 workers with the multiprocessing pool
    my_pool = Pool(processes=8)
    search_results = {}   # f5 search results
    with f5_admin.F5Client(credential, 7, False) as my_f5:       # Initialize a F5 instance
        my_nodes = my_f5.get_node_list()
        print("Total number of known F5 nodes: ", len(my_nodes), "\n")
        for result in my_pool.imap_unordered(search_node, my_nodes):
            if result:
                search_results.update(result)
        print("\n\nSearch results:")
        for node,objs in search_results.items():
            print(len(objs), "match found in F5 node: ", node)
            for key in list(objs.keys()):      # print out the F5 configuration object
                my_f5.print_obj(key,objs[key])

    # Print the confirmation
    print("""
All done. Bye!""")
