#!/bin/sh
(
cat <<EOF
import json
import sys
import os
import logging
import pyzenith
from deployment import containerlist
from deployment import tenants
from util import ossext

FAILED = 1
import subprocess
SUCCESS = 0
DB_USER_NAME = "homeportaldb"
LOG_FILE = os.path.splitext(os.path.realpath(__file__))[0] + '.log'
logging.basicConfig(filename=LOG_FILE, level=logging.DEBUG,
                    format=' %(asctime)s - %(levelname)s - %(message)s')

def check_host_ip(ip_address):
    command = "ip a | grep ' {0}/' >/dev/null 2>&1".format(ip_address)
    ret = subprocess.getstatusoutput(command)
    return ret[0] == 0

def execute_db_command(cursor, relation, old_ids):
    view_id = relation.get("view_id")
    screen_id = relation.get("screen_id")
    order_num = relation.get("order")
    try:
        logging.info(view_id + "<<" + screen_id + "<<" + str(order_num))
        cursor.execute(
            f"SELECT ID FROM HOMEPORTALDB.TBL_VIEW  WHERE VIEW_ID = '{view_id}'");
        row = cursor.fetchall()[0]
        id = row[0]
        logging.info(str(id))
        cursor.execute(f"INSERT INTO HOMEPORTALDB.TBL_PYHSICAL_SCREEN_VIEW VALUES ({screen_id},{id}, 10, {order_num})");
    except pyzenith.DatabaseError:
        log_info = "execute homeportal execute sql error"
        print(log_info)
        logging.debug(log_info)


def repair_portal_data(db_info):
    conn = pyzenith.connect(db_info["connect_ip"], db_info["user"], db_info["pd"],
                            str(db_info["port"]))
    cursor = conn.cursor()
    with open("/tmp/portal_view_relation.properties") as f_json:
        data = json.load(f_json)
        relation_list = data.get("relations")
        old_ids = data.get("old_ids")
        for id in old_ids:
            cursor.execute(
                f"DELETE FROM HOMEPORTALDB.TBL_PYHSICAL_SCREEN_VIEW WHERE VIEW_ID = '{id}'");
        for relation in relation_list:
            execute_db_command(cursor, relation, old_ids)
    cursor.execute("COMMIT")
    cursor.close()
    conn.close()


def get_campus_db_instance():
    db_info = dict()
    all_instance_list = containerlist.ContainerList(tenants.Tenant("CampusInsight")).get_dc_by_type_list("zenith")
    command = "{path}/manager/apps/DBAgent/bin/dbsvc_adm -cmd query-db-instance -type zenith | grep {cluster_name} | grep Master"
    for instance in all_instance_list:
        if "fabricinsightsvr" in instance.get_name():
            if not instance.get_cluster_name():
                cluster_name = instance.get_name()
            else:
                cluster_name = instance.get_cluster_name()
            res = subprocess.getstatusoutput(command.format(
                path=os.environ['INSTALL_ROOT'], cluster_name=cluster_name))[1]
            if not res:
                continue
            db_array = str(res).split()
            current_pd = ossext.Cipher.decrypt0(instance.getDBList().get(DB_USER_NAME, {}).
                                                   get("dbUserPasswd", "").strip())
            if not current_pd:
                continue
            db_info["connect_ip"] = db_array[5]
            db_info["port"] = instance.get_port()
            db_info["user"] = DB_USER_NAME
            db_info["pd"] = current_pd
            return db_info
    return db_info


def main():
    db_info = get_campus_db_instance()
    if not db_info:
        log_info = "campus db instance is not exist"
        print(log_info)
        logging.error(log_info)
        sys.exit(FAILED)
    repair_portal_data(db_info)


if __name__ == '__main__':
    main()
EOF
) > repair_homeportal_data.py
rm -rf /opt/repair_homeportal/
mkdir /opt/repair_homeportal/
cp  repair_homeportal_data.py /opt/repair_homeportal/
chown ossadm:ossgroup /opt/repair_homeportal/
chown ossadm:ossgroup /opt/repair_homeportal/repair_homeportal_data.py
su - ossadm -c "source /opt/oss/manager/bin/engr_profile.sh; python /opt/repair_homeportal/repair_homeportal_data.py"