 #!/bin/sh
(
cat <<EOF
import json
import sys
import os
import logging
import pyzenith

FILE_TRUNC_FLAGS = os.O_RDWR | os.O_CREAT | os.O_TRUNC
FILE_MODES = 0o0200 | 0o0400
from deployment import containerlist
from deployment import tenants
from util import ossext
import subprocess
SUCCESS = 0
FAILED = 1
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 execute_db_command(db_info):
    conn = pyzenith.connect(db_info["connect_ip"], db_info["user"], db_info["pd"],
                            str(db_info["port"]))
    cursor = conn.cursor()

    try:
        cursor.execute(
            "SELECT V.VIEW_ID,P.VIEW_ID,P.SCREEN_ID,P.ORDER_NUM FROM HOMEPORTALDB.TBL_VIEW V,HOMEPORTALDB.TBL_PYHSICAL_SCREEN_VIEW P WHERE  P.VIEW_ID = V.ID AND V.VIEW_ID IS NOT NULL")
    except pyzenith.DatabaseError:
        log_info = "execute homeportal select sql error"
        print(log_info)
        logging.debug(log_info)

    rows = cursor.fetchall()
    if rows:
        json_data = generate_portal_relation_data(rows)
        with os.fdopen(os.open("/tmp/portal_view_relation.properties",
                               FILE_TRUNC_FLAGS, FILE_MODES), 'w') as tmp_file:
            json.dump(json_data, tmp_file, indent=2)

    # cursor.execute("COMMIT")
    cursor.close()
    conn.close()


def generate_portal_relation_data(rows):
    json_data = dict()
    relation_list = []
    old_view_id = []
    for row in rows:
        view_data = dict()
        view_data["view_id"] = row[0]
        view_data["screen_id"] = row[2]
        view_data["order"] = row[3]
        relation_list.append(view_data)
        if row[1] not in old_view_id:
            old_view_id.append(row[1])
    json_data["relations"] = relation_list
    json_data["old_ids"] = old_view_id

    logging.info(f"migration ip info:{json_data}")
    return json_data


def get_campus_db_instance():
    db_info = dict()
    all_instance_list = containerlist.ContainerList(tenants.Tenant("CampusInsight")).getDCByTypeList("zenith")
    command = "{path}/manager/apps/DBAgent/bin/dbsvc_adm -cmd query-db-instance | " \
              "grep {cluster_name} | grep \" {ip} \""
    for instance in all_instance_list:
        if "fabricinsightsvr" in instance.getName():
            if not instance.getClusterName():
                cluster_name = instance.getName()
            else:
                cluster_name = instance.getClusterName()
            status, _ = subprocess.getstatusoutput(command.format(
                path=os.environ['INSTALL_ROOT'], cluster_name=cluster_name, ip=instance.getIP()))
            if status != SUCCESS:
                return db_info
            current_pd = ossext.Cipher.decrypt0(instance.getDBList().get(DB_USER_NAME, {}).
                                                   get("dbUserPasswd", "").strip())
            if not current_pd:
                continue
            db_info["connect_ip"] = instance.getIP()
            db_info["port"] = instance.getPort()
            db_info["user"] = DB_USER_NAME
            db_info["pd"] = current_pd
    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)
    execute_db_command(db_info)


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