#!/bin/sh
(
cat <<EOF
import json
import sys
import os
import logging
import pyzenith
import time
from deployment import containerlist
from deployment import tenants
from util import ossext
import util.httpclient
FAILED = 1
CLOUDSOP_INSTALL_PATH = "/opt/oss"
import ast
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):
    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")
        old_id = old_ids[0]
        cursor.execute(
                f"SELECT VIEW_ID FROM HOMEPORTALDB.TBL_PYHSICAL_SCREEN_VIEW WHERE VIEW_ID = '{old_id}'");
        rows = cursor.fetchall()
        if not rows:
            cursor.close()
            conn.close()
            return
        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)
    cursor.execute("COMMIT")
    cursor.close()
    conn.close()


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 -type zenith | grep {cluster_name} | grep Master"
    for instance in all_instance_list:
        if "fabricinsightsvr" in instance.getName():
            if not instance.getClusterName():
                cluster_name = instance.getName()
            else:
                cluster_name = instance.getClusterName()
            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.getPort()
            db_info["user"] = DB_USER_NAME
            db_info["pd"] = current_pd
            return db_info
    return db_info


def send_rest():
    print("Start to request home portal rest ")
    current_time = 0
    time_strap = int(round(time.time() * 1000))
    request_homeportal_url = f"/rest/homeportalservice/v1/frame-info?v={time_strap}"
    http_get(request_homeportal_url)

def http_get(url):
    ip_val = subprocess.getoutput("hostname -i")
    client = util.httpclient.CommonHttpClient(ip_val, 32018, isHttps=True, gzip=False)
    status, response = client.get(url)
    return status, response

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)
    send_rest()
    repair_portal_data(db_info)


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