from calendar import Calendar, calendar
import csv
import base64
from itertools import chain, count
from random import Random, randint, random
from select import select
import time
import requests
import os
import pymysql
import subprocess
import random
import calendar
import datetime
import runpy
import time
from collections import Counter
import os.path
from pymysql.cursors import DictCursor
from datetime import datetime, timedelta, date
import re
import pexpect
import json

data_insert_limit = 100
counts = 0
todayDate = date.today()
down_count_threshold = 3
productionMode = True


log_file_path = "script_log.txt"
def log(message):
    with open(log_file_path, "a") as log_file:
        log_file.write(message + "\n")

def format_time_difference(seconds):
    td = timedelta(seconds=seconds)
    hours, remainder = divmod(td.seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    return f"{hours:02}:{minutes:02}:{seconds:02}"

def sudo(command):
    return subprocess.run(["sudo"] + command, capture_output=True, encoding="utf8")

def getUser():
    if productionMode == True:
        return "openvpn-purple"
    else:
        return "root"


def getUserPwd():
    if productionMode == True:
        return "I5q50q154BjF"
    else:
        return "password"


def getDbName():
    if productionMode == True:
        return "openvpnpurple"
    else:
        return "ovpn"


def getHost():
    if productionMode == True:
        return "172.16.16.82"
    else:
        return "localhost"


def getOvpnTableName():
    if productionMode == True:
        return "ovpn_servers_new"
    else:
        return "ovpn_servers_new"


def getCountriesTableName():
    if productionMode == True:
        return "countries"
    else:
        return "countries"


def getPhpConnectionPath():
    if productionMode == True:
        return "http://localhost/ovpnresearch/check_connection.php"
    else:
        return "http://localhost/vpn_server_main_script_research/check_connection.php"
    
def getOvpnMainFilePath():
    if productionMode == True:
        return "Ovpn/"
    else:
        return "Ovpn_new/"


# Host Details
live_user = getUser()
live_user_pwd = getUserPwd()
live_database_name = getDbName()
live_host = getHost()
live_ovpn_table_name = getOvpnTableName()
live_country_table_name = getCountriesTableName()
decode_vpn_path = "decodeOvpn/"
ovpn_path = getOvpnMainFilePath()
connection_php_path = getPhpConnectionPath()

# TableColumn


# def next_weekday(d, weekday):
#     days_ahead = weekday - d.weekday()
#     if days_ahead < 0:  # Target day already happened this week
#         days_ahead += 7
#     return d + datetime.timedelta(days_ahead)


# next_firday = next_weekday(todayDate, 5)  # 0 = Monday, 1=Tuesday, 2=Wednesday...


def update_script_run_counter():
    counter_file_path = "script_run_counter.txt"

    # Check if the counter file exists
    if not os.path.exists(counter_file_path):
        # If the file doesn't exist, create it and initialize the counter to 1
        with open(counter_file_path, "w") as counter_file:
            counter_file.write("1")
        return 1
    else:
        # If the file exists, read the current counter value, increment it, and update the file
        with open(counter_file_path, "r+") as counter_file:
            counter = int(counter_file.read())
            counter += 1
            counter_file.seek(0)
            counter_file.write(str(counter))
        return counter


def ovpnConnected(filepath):
    url = connection_php_path

    # Assuming the API expects the 'filepath' parameter
    payload = {"filepath": filepath}

    response = requests.post(url, data=payload)

    if response.status_code == 200:
        data = response.json()
        return data["isConnected"]
    else:
        return f"Error: {response.status_code}, {response.text}"


def checkcountrydata():
    try:
        db = pymysql.connect(
            host=live_host,
            user=live_user,
            passwd=live_user_pwd,
            database=live_database_name,
        )
        # db = pymysql.connect(host = "104.248.13.122",user = "ovpnuser",passwd = "y7OZho5X4jejchHM",database = "ovpn-temp")
        cursor = db.cursor(DictCursor)
        sql = f"select country_code from {live_country_table_name}"
        cursor.execute(sql)
        number0flines = cursor.execute(sql)
        results = cursor.fetchall()
        webcountrycode = []
        commanlist = []
        sqlcountrycode = []
        CSV_URL = "http://www.vpngate.net/api/iphone/"
        with requests.Session() as s:
            download = s.get(CSV_URL)
            decoded_content = download.content.decode("utf-8")
            cr = csv.reader(decoded_content.splitlines(), delimiter=",")
            my_list = list(cr)
        if number0flines == 0:
            for contrydata in my_list[2:-1]:
                countrycode = contrydata[6]
                webcountrycode.append(countrycode)

            commanlist = list(set(webcountrycode))

            for checklist in commanlist:
                for i in range(2, len(my_list)):
                    if my_list[i][6] == checklist:
                        arraydata = my_list[i]
                        cursor = db.cursor(DictCursor)
                        query = "INSERT INTO {} (country , country_code , created_at , updated_at, premium, is_active) VALUES (%s , %s , %s ,%s , %s , %s)".format(
                            live_country_table_name
                        )
                        dt = time.gmtime()
                        ts = calendar.timegm(dt)
                        alldata = (
                            arraydata[5],
                            arraydata[6],
                            ts,
                            ts,
                            1,
                            0,
                        )
                        a = cursor.execute(query, alldata)
                        results = cursor.fetchall()
                        db.commit()
                        break
        else:
            for codesof in results:
                codes = codesof["country_code"]
                sqlcountrycode.append(codes)
            for contrydata in my_list[2:-1]:
                countrycode = contrydata[6]
                webcountrycode.append(countrycode)

            commanlist = list(set(webcountrycode))
            neewcode = list(set(commanlist) - set(sqlcountrycode))
            for checklist in neewcode:
                for i in range(2, len(my_list)):
                    if my_list[i][6] == checklist:
                        arraydata = my_list[i]
                        cursor = db.cursor(DictCursor)
                        query = "INSERT INTO {} (country , country_code , created_at , updated_at , is_active) VALUES (%s , %s , %s ,%s , %s)".format(
                            live_country_table_name
                        )
                        dt = time.gmtime()
                        ts = calendar.timegm(dt)
                        alldata = (
                            arraydata[5],
                            arraydata[6],
                            ts,
                            ts,
                            0,
                        )
                        a = cursor.execute(query, alldata)
                        results = cursor.fetchall()
                        db.commit()
                        break
        db.close()
    except Exception as e:
        print(e)
        runpy.run_path(path_name="kr_temporary_server.py")


def insertwithlimit():
    try:
        db = pymysql.connect(
            host=live_host,
            user=live_user,
            passwd=live_user_pwd,
            database=live_database_name,
        )
        # db = pymysql.connect(host = "104.248.13.122",user = "ovpnuser",passwd = "y7OZho5X4jejchHM",database = "ovpn-temp")
        cursor = db.cursor(DictCursor)
        sql = f"select country_code from {live_country_table_name}"

        cursor.execute(sql)

        number0flines = cursor.execute(sql)
        results = cursor.fetchall()
        webcountrycode = []
        commanlist = []
        sqlcountrycode = []
        sqliparr = []
        webarrip = []
        mysqlarrip = []
        newmylist = []
        webcountryip = []
        newcode = []
        CSV_URL = "http://www.vpngate.net/api/iphone/"
        with requests.Session() as s:
            download = s.get(CSV_URL)
            decoded_content = download.content.decode("utf-8")
            cr = csv.reader(decoded_content.splitlines(), delimiter=",")
            my_list = list(cr)
            my_list.remove(my_list[0])
            my_list.remove(my_list[1])
            my_list.remove(my_list[-1])

        my_list = my_list[2:-1]

        # for record in filtered_list:
        #     print(record[1])
        #     exit()
        cursor = db.cursor(DictCursor)

        sql = f"SELECT country_id, (SELECT country_code from {live_country_table_name} as c WHERE c.country_id = v.country_id) as country_code FROM {live_ovpn_table_name} v GROUP by country_id"

        cursor.execute(sql)

        number0flines = cursor.execute(sql)
        checkdata = cursor.fetchall()

        for arrRowsData in my_list:
            ipcheck = arrRowsData[1]
            # print(ipcheck)
            webcountryip.append(ipcheck)
            # webcountrycode.append(countrycode)

        # exit()
        for arrRowsData in my_list:
            ipcheck = arrRowsData[6]
            # print(ipcheck)
            webcountrycode.append(ipcheck)
        # for codesof in results:
        #         codes = codesof[0]
        #         sqlcountrycode.append(codes)
        # print("sql country code list" ,list(set(sqlcountrycode)))

        commanlist = list(set(webcountrycode))
        cursor = db.cursor(DictCursor)
        sql = f"select * from {live_ovpn_table_name}"

        cursor.execute(sql)
        result = cursor.fetchall()
        # print('result', result)

        for arrRowsData in my_list:
            ipcheck = arrRowsData[1]
            # print(ipcheck)
            # print(ipcheck)
            webarrip.append(ipcheck)

        for iplist in result:
            # print(result)
            # exit()
            hostname = iplist["ip_address"]

            mysqlarrip.append(hostname)

        newiplist = list(set(webarrip) - set(mysqlarrip))

        print(" total new ip list  = ", len(newiplist))
        # exit()
        for codelist in checkdata:
            newcode.append(codelist["country_code"])

        # print(commanlist, newcode)
        updatedlist = list(set(commanlist) - set(newcode))
        # print(updatedlist)
        # exit()
        # print("comman list = ", commanlist)
        # print("newcode list = ", set(newcode))
        # print("updated list = ", updatedlist)
        # exit()

        # counts = 0
        # print(len(filtered_list))
        # exit()
        for temp in newcode:
            counts = 0
            for abc in my_list:
                if abc[6] == temp:
                    if counts == data_insert_limit:
                        counts = 0
                        break
                    else:
                        # print(abc)
                        counts = counts + 1
                        newmylist.append(abc)

        print("newmylist  -------->", len(newmylist))
        print("mylist  -------->", len(my_list))
        # exit()
        cursor = db.cursor(DictCursor)
        sql = f"select * from {live_ovpn_table_name}"
        cursor.execute(sql)
        number0flines = cursor.execute(sql)
        ipfetch = cursor.fetchall()

        for iplist in ipfetch:
            hostname = iplist["ip_address"]
            sqliparr.append(hostname)

        for i in sqliparr:
            for abc in newmylist:
                if i == abc[1]:
                    newmylist.remove(abc)

        print("newmylist  -------->", len(newmylist))

        cursor = db.cursor(DictCursor)
        query = f"SELECT country_id,(SELECT country_code from {live_country_table_name} c WHERE c.country_id = vs.country_id) as country_code, COUNT(country_id) countrycount FROM {live_ovpn_table_name} as vs GROUP by country_id"
        cursor.execute(query)
        checktotalcount = cursor.fetchall()
        # print("total data = " , checktotalcount)
        # print(checktotalcount)
        # exit()
        cursor.close()
        for i in range(0, len(checktotalcount)):
            countrynumber = checktotalcount[i]["country_code"]
            for abc in newmylist:
                # print("newcount =" , newcount)
                # print(abc[6].upper(), countrynumber)
                if abc[6].upper() == countrynumber:
                    ip_address = abc[1]

                    # if ip_address in unique_ip_addresses:
                    #     print(f"Skipping duplicate IP address: {ip_address}")
                    #     continue
                    arrRowsData = abc
                    hostname = abc[0]
                    a = base64.b64decode(arrRowsData[14])

                    cursor = db.cursor(DictCursor)
                    query = "select country_id from {} WHERE country_code = %s".format(
                        live_country_table_name
                    )
                    
                    alldata = arrRowsData[6]
                    print("new", alldata)
                    b = cursor.execute(query, alldata)
                    print(query)
                    c_id = cursor.fetchall()
                    country_id = c_id[0]["country_id"]
                    print("new", country_id)
                    dt = time.gmtime()
                    ts = calendar.timegm(dt)
                    os.makedirs(decode_vpn_path, exist_ok=True)

                    file_name_aaa = (
                        decode_vpn_path + hostname + "_" + arrRowsData[1] + ".text"
                    )
                    with open(file_name_aaa, "wb") as fh:
                        fh.write(a)

                    os.makedirs(ovpn_path, exist_ok=True)
                    file_name_bbb = (
                        ovpn_path + hostname + "_" + arrRowsData[1] + ".ovpn"
                    )
                    f = open(file_name_bbb, "a+")
                    with open(file_name_aaa, "r") as thelib:
                        mydata = thelib.readlines()
                    filedata = []
                    for data in mydata:
                        if (
                            data.startswith("#")
                            or data.startswith(" ")
                            or data.startswith("\n")
                        ):
                            continue
                        else:
                            # print("Main data",data)
                            f.write(data)

                    f.close()
                    with open(file_name_bbb, "r") as thelib:
                        reopendata = thelib.read()

                    country_code_2 = arrRowsData[6]
                    # print("newmylist_ip = ", ip_address)
                    query = "INSERT INTO {} (country_id, ip_address, ovpn, created_at , updated_at, country_code) VALUES (%s, %s, %s, %s, %s, %s)".format(
                        live_ovpn_table_name
                    )
                    values = (
                        country_id,
                        ip_address,
                        reopendata,
                        ts,
                        ts,
                        country_code_2.upper(),
                    )
                    # if ip_address not in unique_ip_addresses:
                    cursor.execute(query, values)
                    db.commit()
                    last_inserted_id = cursor.lastrowid
                    # print(last_inserted_id)
                    # exit()
                    # Rename the file_bbb
                    new_filename = f"{ovpn_path}{last_inserted_id}_{ip_address}.ovpn"
                    os.rename(file_name_bbb, new_filename)

        for temp in updatedlist:
            counts = 0
            for abc in my_list[2:-1]:
                if abc[6].upper() == temp:
                    ip_address = abc[1]
                    hostname = abc[0]

                    # if ip_address in unique_ip_addresses:
                    #     print(f"Skipping duplicate IP address: {ip_address}")
                    #     continue

                    a = base64.b64decode(abc[-1])
                    cursor = db.cursor(DictCursor)
                    query = "select country_id from {} WHERE country_code = %s".format(
                        live_country_table_name
                    )                    
                    
                    alldata = abc[6]
                    # print("alldata = ", alldata)                    
                    print("updated", alldata)
                    b = cursor.execute(query, alldata)
                    print(query)
                    c_id_updated = cursor.fetchall()
                    # print("result = ",results)
                    country_id = c_id_updated[0]["country_id"]
                    print("updated", country_id)
                    # print("updatedlist_ip = ", ip_address)
                    db.commit()
                    os.makedirs(decode_vpn_path, exist_ok=True)

                    file_name_aaa = decode_vpn_path + hostname + "_" + abc[1] + ".text"
                    with open(file_name_aaa, "wb") as fh:
                        fh.write(a)

                    os.makedirs(ovpn_path, exist_ok=True)

                    file_name_bbb = ovpn_path + hostname + "_" + abc[1] + ".ovpn"
                    f = open(file_name_bbb, "a+")
                    with open(file_name_aaa, "r") as thelib:
                        mydata = thelib.readlines()
                    filedata = []
                    for data in mydata:
                        if (
                            data.startswith("#")
                            or data.startswith(" ")
                            or data.startswith("\n")
                        ):
                            continue
                        else:
                            # print("Main data",data)
                            f.write(data)

                    f.close()
                    with open(file_name_bbb, "r") as thelib:
                        reopendata = thelib.read()

                    cursor = db.cursor(DictCursor)
                    # dt = time.gmtime()
                    dt = time.gmtime()
                    ts = calendar.timegm(dt)

                    query = "INSERT INTO {} (country_id, ip_address, ovpn, created_at , updated_at, country_code) VALUES (%s ,%s ,%s, %s, %s, %s)".format(
                        live_ovpn_table_name
                    )
                    alldata = (
                        country_id,
                        ip_address,
                        reopendata,
                        ts,
                        ts,
                        abc[6].upper(),
                    )
                    cursor.execute(query, alldata)

                    db.commit()
                    last_inserted_id = cursor.lastrowid
                    # print(last_inserted_id)

                    # Rename the file_bbb
                    new_filename = f"{ovpn_path}{last_inserted_id}_{ip_address}.ovpn"
                    os.rename(file_name_bbb, new_filename)

        db.close()
        # print("last line")
        files = os.listdir(decode_vpn_path)

        # Iterate through the files and remove them
        for file in files:
            file_path = os.path.join(decode_vpn_path, file)
            if os.path.isfile(file_path):
                os.remove(file_path)

        # print("text Files removed successfully.")

    except Exception as e:
        print(e)
        runpy.run_path(path_name="kr_temporary_server.py")


def pingCount():
    # try:
        # Get the current script run counter
        # script_run_count = update_script_run_counter()

        # print(f"This is the {script_run_count}th time the script has run.")
        db = pymysql.connect(
            host=live_host,
            user=live_user,
            passwd=live_user_pwd,
            database=live_database_name,
        )
        # cursor = db.cursor(DictCursor)
        # delete_condition = "ping_count < -2"
        # select_ping_query = (
        #     f"SELECT * FROM {live_ovpn_table_name} WHERE {delete_condition}"
        # )
        # cursor.execute(select_ping_query)
        # selected_data = cursor.fetchall()
        # for data in selected_data:
        #     server_id = data["server_id"]
        #     ip_address = data["ip_address"]
        #     file_path = ovpn_path + str(server_id) + "_" + ip_address + ".ovpn"
        #     if os.path.isfile(file_path):
        #         os.remove(file_path)
        #         print(f"Removed: {file_path}")
        # # print("Ovpn Files removed successfully.")
        # # exit()
        # db.commit()

        # delete_query = f"DELETE FROM {live_ovpn_table_name} WHERE {delete_condition}"
        # cursor.execute(delete_query)
        # db.commit()

        cursor = db.cursor(DictCursor)
        sql = f"select * from {live_ovpn_table_name}"
        cursor.execute(sql)
        number0flines = cursor.execute(sql) 
        ipfetch = cursor.fetchall()
        for iplist in ipfetch:
            # print(iplist[2])
            # exit()
            # ccc = time.strftime("%H:%M:%S")
            # current_time = datetime.datetime.strptime(
            #     ccc, "%H:%M:%S"
            # ).time()  # time.strftime("%H:%M:%S")
            # startTime = datetime.datetime.strptime("00:00:00", "%H:%M:%S").time()
            # endTime = datetime.datetime.strptime("00:35:00", "%H:%M:%S").time()
            ip_address = iplist["ip_address"]
            server_id = iplist["server_id"]

            cursor = db.cursor(DictCursor)
            query = "select ping_count, ovpn from {} WHERE ip_address = %s AND server_id = %s".format(
                live_ovpn_table_name
            )
            qr_parm = (ip_address, server_id)
            cursor.execute(query, qr_parm)
            data = cursor.fetchall()
            pingCount = data[0]["ping_count"]
            ovpn = data[0]["ovpn"]

            filepath = ovpn_path + str(server_id) + "_" + ip_address + ".ovpn"
            check_file = os.path.exists(filepath)
            print(check_file)

            if check_file == False:
                with open(filepath, "w") as fh:
                    fh.write(ovpn)

            response = ovpnConnected(filepath)

            # subprocess.run(["sudo", "killall", "openvpn"])
            print("pingcount before:", pingCount)
            print("response: " + ip_address, response)
            # exit()
            # if todayDate == next_firday:
            #     if current_time > startTime and current_time < endTime:
            #         sql = "UPDATE {} SET ping_count = %s".format(live_ovpn_table_name)
            #         ip = 0
            #         a = cursor.execute(sql, ip)
            #         results = cursor.fetchall()
            #     else:
            # if response == True:
            #     # print(pingCount[0][0]+1)
            #     dt = time.gmtime()
            #     ts = calendar.timegm(dt)
            #     sql = "UPDATE {} SET is_active  = %s , ping_count = %s, updated_at = %s  WHERE ip_address = %s AND server_id = %s".format(live_ovpn_table_name)
            #     ip = (1, pingCount + 1, ts, ip_address, server_id)
            #     a = cursor.execute(sql, ip)
            #     results = cursor.fetchall()
            #     print(a)
            #     db.commit()
            # else:
            #     # print(pingCount[0][0]-1)
            #     print(ip_address, "is down")
            #     # sqliparr.append(hostname)
            #     dt = time.gmtime()
            #     ts = calendar.timegm(dt)
            #     sql = "UPDATE {} SET is_active = %s , pings_count = %s, updated_at = %s  WHERE ip_address = %s AND server_id = %s".format(live_ovpn_table_name)
            #     ip = (0, pingCount - 1, ts, ip_address, server_id)
            #     a = cursor.execute(sql, ip)
            #     results = cursor.fetchall()
            #     db.commit()

            #     query = "SELECT ping_count FROM {} WHERE ip_address = %s AND server_id = %s".format(live_ovpn_table_name)
            #     ip = _(ip_address, server_id)
            #     cursor.execute(query, ip)
            #     updated_ping_count = cursor.fetchone()[0]
            #     print("ping count after:", updated_ping_count)


            if response == True:
                # print(pingCount[0][0]+1)
                dt = time.gmtime()
                ts = calendar.timegm(dt)
                sql = "UPDATE {} SET is_active  = %s , ping_count = %s, updated_at = %s  WHERE ip_address = %s AND server_id = %s".format(
                    live_ovpn_table_name
                )
                ip = (1, pingCount + 1, ts, ip_address, server_id)
                a = cursor.execute(sql, ip)
                results = cursor.fetchall()

                db.commit()
                run_count = 0
                start_time = time.time()
                run_count += 1
                
                # Simulate function calls (replace with your actual functions)

                # checkcountrydata()
                # insertwithlimit()
                
                
                # speedtest_cmd = "speedtest [-f] --format=json"
                # returned_value = subprocess.run(speedtest_cmd, shell=True)  # returns the exit code in unix
                speedtest_result = subprocess.run(["speedtest","--accept-license",  "[-f]", "--format=json"], capture_output=True, text=True)
                if speedtest_result.returncode == 0:
                    speedtest_data = json.loads(speedtest_result.stdout)
                    # exit()

                    if "packetLoss" in speedtest_data:
                        print("packetLoss", speedtest_data["packetLoss"])
                        packet_loss = speedtest_data["packetLoss"]
                        print("Packet Loss in condition:", packet_loss)

                        if packet_loss <= 5:
                            server_quality = "excellent"
                        elif 5 < packet_loss <= 10:
                            server_quality = "very-good"
                        elif 10 < packet_loss <= 20:
                            server_quality = "good"
                        else:
                            server_quality = "weak"
                        
                        print(server_quality)
                        sql = "UPDATE {} SET quality_of_servers = %s  WHERE ip_address = %s AND server_id = %s".format(
                            live_ovpn_table_name
                        )
                        ip = (server_quality, ip_address, server_id)
                        a = cursor.execute(sql, ip)

                        db.commit()
                    else:
                        print("packetloss fail", speedtest_data)
                        print("Packet Loss information not found in the output.")
                        # print(server_quality)
                        sql = "UPDATE {} SET quality_of_servers = %s  WHERE ip_address = %s AND server_id = %s".format(
                            live_ovpn_table_name
                        )
                        ip = ("weak", ip_address, server_id)
                        a = cursor.execute(sql, ip)

                        db.commit()
                else:
                    print("else_speedtest_result", speedtest_result)
                    print("return_code", speedtest_result.returncode)
                    sql = "UPDATE {} SET quality_of_servers = %s  WHERE ip_address = %s AND server_id = %s".format(
                            live_ovpn_table_name
                    )
                    ip = ("weak", ip_address, server_id)
                    a = cursor.execute(sql, ip)

                    db.commit()

                end_time = time.time()
                time_difference = end_time - start_time
                formatted_time_difference = format_time_difference(time_difference)
                

                log(f"Start Time 1: {datetime.fromtimestamp(start_time).strftime('%Y-%m-%d %H:%M:%S')}")
                log(f"Script Run Count: {run_count}")
                log(f"End Time 1: {datetime.fromtimestamp(end_time).strftime('%Y-%m-%d %H:%M:%S')}")
                log(f"Time Difference 1: {formatted_time_difference}\n")
                
                
                sudo(["killall"] + ["openvpn"])

            else:
                print(pingCount)
                print(ip_address, "is down")
                dt = time.gmtime()
                ts = calendar.timegm(dt)
                sql = "UPDATE {} SET is_active = %s , ping_count = %s, updated_at = %s, quality_of_servers = %s  WHERE ip_address = %s AND server_id = %s".format(
                    live_ovpn_table_name
                )
                ip = (0, pingCount - 1, ts, "false-weak", ip_address, server_id)
                a = cursor.execute(sql, ip)
                results = cursor.fetchall()
                db.commit()

                query = "SELECT ping_count FROM {} WHERE ip_address = %s AND server_id = %s".format(
                    live_ovpn_table_name
                )
                ip = (ip_address, server_id)
                cursor.execute(query, ip)
                updated_ping_count = cursor.fetchone()["ping_count"]
                print("ping count after:", updated_ping_count)
                
                sudo(["killall"] + ["openvpn"])

            time.sleep(1)

        db.close()

    # except Exception as e:
    #     print(e)
        # runpy.run_path(path_name="kr_temporary_server.py")


def main():
    run_count = 0
    
    while True:
        start_time = time.time()
        run_count += 1
        print("script_start_time", start_time)
        # Simulate function calls (replace with your actual functions)

        # checkcountrydata()
        # insertwithlimit()
        pingCount()
        
        end_time = time.time()
        time_difference = end_time - start_time
        formatted_time_difference = format_time_difference(time_difference)
        print("script_end_time", end_time)
        

        log(f"Start Time script: {datetime.fromtimestamp(start_time).strftime('%Y-%m-%d %H:%M:%S')}")
        log(f"Script Run Count script: {run_count}")
        log(f"End Time script: {datetime.fromtimestamp(end_time).strftime('%Y-%m-%d %H:%M:%S')}")
        log(f"Time Difference script: {formatted_time_difference}")
        
if __name__ == "__main__":
    main()

