#!/usr/bin/python3

import json
import sqlite3
# from db import *
from globalSettings import *
from global_func import *
import cgi
import cgitb
import os
import filecmp
import shutil

cgitb.enable()

conn = sqlite3.connect(DBPath)
conn.text_factory = str
c = conn.cursor()


print("Content-type:/text/json\r\n\r\n")


if (GUI == true):
    form = cgi.FieldStorage()
    request_Type = form.getvalue('RequestType')

def restart():
    password = form.getvalue('password')
    fw_name = form.getvalue('fw_name')
    c.execute('select * from person where password = ?',[password])
    fw_name = fw_name.split(".zip")[0]
    exists = c.fetchone()
    if exists is not None:
        restartGUI(fw_name)
        c.execute("update versionControl set status = ?",["False"])
        conn.commit()
        c.execute("insert into versionControl (fw_name,status,cr_date) values(?,?,datetime())",[fw_name,"True"])
        conn.commit()
        print(json.JSONEncoder().encode({"status" : "success"}))
    else:
        print(json.JSONEncoder().encode({"status" : "Fail","description" : "Invalid Password"}))
    c.close()
    conn.close()

def activate():
    password = form.getvalue('password')
    fw_name = form.getvalue('fw_name')
    c.execute('select * from person where password = ?',[password])
    exists = c.fetchone()
    if exists is not None:
        restartGUI(fw_name)
        c.execute("update versionControl set status = ?",["False"])
        conn.commit()
        c.execute("update versionControl  set status = ? where fw_name =?",["True",fw_name])
        conn.commit()
        print(json.JSONEncoder().encode({"status" : "success"}))
    else:
        print(json.JSONEncoder().encode({"status" : "Fail","description" : "Invalid Password"}))
    c.close()
    conn.close()
def getFw():
    dirArray = []
    c.execute('select * from versionControl ORDER BY cr_date DESC LIMIT 3')
    cols = c.fetchall()
    for item in cols:
        dirArray.append({"fw_name": item[1],"status" :item[2],"upload_date" :item[3]})
    c.close()
    conn.close()
    print(json.JSONEncoder().encode({"dirArray": dirArray}))


def restartGUI(fw_name):
    pilotCCMPath = '/home/pilotCCM'
    pilotPath = '/var/www/Lyra-TL'
    uploadFolderPath = "/mnt/xdata/uploads/"+fw_name
    folder_to_move_home = os.path.join(uploadFolderPath, 'pilotCCM')
    folder_to_move_var_www = os.path.join(uploadFolderPath, 'Lyra-TL')
    # if os.path.exists(folder_to_move_home):
    #     shutil.move(folder_to_move_home, pilotCCMPath)
    # if os.path.exists(folder_to_move_var_www):
    #     shutil.move(folder_to_move_var_www, pilotPath)
    replace_changed_files(pilotPath,folder_to_move_var_www)
    replace_changed_files(pilotCCMPath,folder_to_move_home)
    return True

def replace_changed_files(existing_folder, new_folder):
    for root, dirs, files in os.walk(existing_folder):
        for file in files:
            existing_file_path = os.path.join(root, file)
            new_file_path = os.path.join(new_folder, os.path.relpath(existing_file_path, existing_folder))
            try:
                if os.path.exists(new_file_path):
                    if not filecmp.cmp(existing_file_path, new_file_path, shallow=False):
                        shutil.copy2(new_file_path, existing_file_path)
                else:
                    shutil.copy2(existing_file_path, new_file_path)
            except Exception as e:
                pass
    return True


if request_Type == 'restart':
    restart()
elif request_Type == "activate":
    activate()
elif request_Type == "getFw":
    getFw()