[root@uswaa-dopoorp01 Opsview_upgrade]# cat argsanalyzer.py
#!/usr/bin/env python3

import subprocess
import shlex
import sys
import os

# Suppress shlex debug output by redirecting it
class QuietShlex(shlex.shlex):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.debug = 0

shlex.shlex = QuietShlex

# Ensure no debug variables are set
os.environ.pop('PYTHONWARNINGS', None)
os.environ.pop('SHLEX_DEBUG', None)

tables_columns = [
    ('args', 'servicechecks'),
    ('args', 'servicecheckhostexceptions'),
    ('args', 'servicecheckhosttemplateexceptions'),
    ('args', 'servicechecktimedoverridehostexceptions'),
    ('args', 'servicechecktimedoverridehosttemplateexceptions'),
]

# Dictionary to store service check ids from the servicechecks table
servicecheck_ids = {}

def run_command(cmd):
    """Run a shell command and return its output."""
    try:
        output = subprocess.run(shlex.split(cmd), check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return output.stdout.decode('utf-8')
    except subprocess.CalledProcessError as e:
        print(f"Command failed: {e}")
        sys.exit(1)

# Process each table and column
for column, table in tables_columns:
    print(f"'{table}' Results:")

    cmd = f"/opt/opsview/coreutils/utils/cx opsview 'SELECT id,{column} FROM opsview.{table}'"

    output_str = run_command(cmd)
    values = output_str.split('\n')[:-1]  # Remove the extra newline

    if not values:
        print(f"No data found in table '{table}'")
        continue

    # Handle servicechecks table specially to collect IDs
    if table == 'servicechecks':
        for value in values[1:]:
            parts = value.split(maxsplit=1)
            if len(parts) < 2:
                print(f"Malformed line in servicechecks table: {value}")
                continue
            row_id, args_string = parts
            try:
                shlex.split(args_string)
            except Exception:
                print(f"{row_id} =====> FAILED! Args: {args_string}")
            # Store IDs in dictionary
            servicecheck_ids[row_id] = args_string

    # Handle other tables and check against collected IDs
    else:
        for value in values[1:]:
            parts = value.split(maxsplit=1)
            if len(parts) < 2:
                print(f"Malformed line in table '{table}': {value}")
                continue
            row_id, args_string = parts
            try:
                shlex.split(args_string)
            except Exception:
                if row_id in servicecheck_ids:
                    print(f"{row_id} =====> FAILED! Service Check ID from servicechecks table: {row_id}")
                else:
                    print(f"{row_id} =====> FAILED! Args: {args_string}")
