#!/usr/bin/python3
# Copyright 2023-2024 Centreon
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# For more information : contact@centreon.com
#
# This script is a little tcp server working on port 5669. It can simulate
# a cbd instance. It is useful to test the validity of BBDO packets sent by
# centengine.
import sys, getopt
import pymysql.cursors

def init_globals():
    with open("/tmp/db_variables.resource", "r") as f:
        content = f.readlines()
        for line in content:
            if "DBHost" in line:
                global DB_HOST
                DB_HOST = line.split()[1]
            elif "DBUser" in line:
                global DB_USER
                DB_USER = line.split()[1]
            elif "DBPass" in line:
                global DB_PASS
                DB_PASS = line.split()[1]
            elif "DBName" in line:
                global DB_NAME
                DB_NAME = line.split()[1]

def main(argv):
    try:
        opts, args = getopt.getopt(argv,"i:",["id="])
    except getopt.GetoptError:
        print('check_centreon_bam -i <id>')
        sys.exit(2)

    id = 0
    for opt, arg in opts:
        print(f"COUCOU1 {opt} {arg}")
        if opt == '-h':
            print('check_centreon_bam -i <id>')
            sys.exit()
        elif opt in ("-i", "--id"):
            if arg.isdigit():
                id = int(arg)

    if not id:
        print('check_centreon_bam -i <id>')
        sys.exit(2)

    init_globals()

    connection = pymysql.connect(host=DB_HOST,
                                 user=DB_USER,
                                 password=DB_PASS,
                                 database=DB_NAME,
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

    with connection:
        with connection.cursor() as cursor:
            # Read a single record
            sql = f"SELECT comment, state_source FROM mod_bam WHERE ba_id={id}"
            cursor.execute(sql)
            result = cursor.fetchall()
            for r in result:
                print(r['comment'])
                sys.exit(r['state_source'])

if __name__ == "__main__":
    main(sys.argv[1:])
