#!/usr/bin/env python3.10
# -*- coding: utf-8 -*-
import os

os.system("pip install requests >/dev/null")
import requests
from urllib.request import Request, urlopen
import random
import shutil
import socket
import string
import subprocess
import sys
import time
import json
import base64

# import urllib2
from itertools import cycle, zip_longest as izip
from itertools import zip_longest

rDownloadURL = {
    "main": "http://sehara.eu:5656/Infinity/infinity.tar.gz",
    "sub": "http://sehara.eu:5656/Infinity/sub_infinity.tar.gz",
}
rPackages = [
    "libcurl4",
    "libxslt1-dev",
    "libgeoip-dev",
    "e2fsprogs",
    "wget",
    "mcrypt",
    "nscd",
    "htop",
    "zip",
    "unzip",
    "mc",
    "libpng16-16",
    "libzip5",
    "python-is-python2",
    "mariadb-server",
]
# ubuntu18#rPackages = ["libcurl3", "libxslt1-dev", "libgeoip-dev", "e2fsprogs", "wget", "mcrypt", "nscd", "htop", "zip", "unzip", "mc", "mariadb-server"]
rInstall = {"MAIN": "main", "LB": "sub"}
eMySQLenc = "IyBYdHJlYW0gQ29kZXMKCltjbGllbnRdCnBvcnQgICAgICAgICAgICA9IDMzMDYKCltteXNxbGRfc2FmZV0KbmljZSAgICAgICAgICAgID0gMAoKW215c3FsZF0KdXNlciAgICAgICAgICAgID0gbXlzcWwKcG9ydCAgICAgICAgICAgID0gNzk5OQpiYXNlZGlyICAgICAgICAgPSAvdXNyCmRhdGFkaXIgICAgICAgICA9IC92YXIvbGliL215c3FsCnRtcGRpciAgICAgICAgICA9IC90bXAKbGMtbWVzc2FnZXMtZGlyID0gL3Vzci9zaGFyZS9teXNxbApza2lwLWV4dGVybmFsLWxvY2tpbmcKc2tpcC1uYW1lLXJlc29sdmU9MQoKYmluZC1hZGRyZXNzICAgICAgICAgICAgPSAqCmtleV9idWZmZXJfc2l6ZSA9IDEyOE0KCm15aXNhbV9zb3J0X2J1ZmZlcl9zaXplID0gNE0KbWF4X2FsbG93ZWRfcGFja2V0ICAgICAgPSA2NE0KbXlpc2FtLXJlY292ZXItb3B0aW9ucyA9IEJBQ0tVUAptYXhfbGVuZ3RoX2Zvcl9zb3J0X2RhdGEgPSA4MTkyCnF1ZXJ5X2NhY2hlX2xpbWl0ICAgICAgID0gNE0KcXVlcnlfY2FjaGVfc2l6ZSAgICAgICAgPSAyNTZNCgoKZXhwaXJlX2xvZ3NfZGF5cyAgICAgICAgPSAxMAptYXhfYmlubG9nX3NpemUgICAgICAgICA9IDEwME0KCm1heF9jb25uZWN0aW9ucyAgPSAyMDAwMApiYWNrX2xvZyA9IDQwOTYKb3Blbl9maWxlc19saW1pdCA9IDIwMjQwCmlubm9kYl9vcGVuX2ZpbGVzID0gMjAyNDAKbWF4X2Nvbm5lY3RfZXJyb3JzID0gMzA3Mgp0YWJsZV9vcGVuX2NhY2hlID0gNDA5Ngp0YWJsZV9kZWZpbml0aW9uX2NhY2hlID0gNDA5NgoKCnRtcF90YWJsZV9zaXplID0gMUcKbWF4X2hlYXBfdGFibGVfc2l6ZSA9IDFHCgppbm5vZGJfYnVmZmVyX3Bvb2xfc2l6ZSA9IDEwRwppbm5vZGJfYnVmZmVyX3Bvb2xfaW5zdGFuY2VzID0gMTAKaW5ub2RiX3JlYWRfaW9fdGhyZWFkcyA9IDY0Cmlubm9kYl93cml0ZV9pb190aHJlYWRzID0gNjQKaW5ub2RiX3RocmVhZF9jb25jdXJyZW5jeSA9IDAKaW5ub2RiX2ZsdXNoX2xvZ19hdF90cnhfY29tbWl0ID0gMAppbm5vZGJfZmx1c2hfbWV0aG9kID0gT19ESVJFQ1QKcGVyZm9ybWFuY2Vfc2NoZW1hID0gMAppbm5vZGItZmlsZS1wZXItdGFibGUgPSAxCmlubm9kYl9pb19jYXBhY2l0eT0yMDAwMAppbm5vZGJfdGFibGVfbG9ja3MgPSAwCmlubm9kYl9sb2NrX3dhaXRfdGltZW91dCA9IDAKI2lubm9kYl9kZWFkbG9ja19kZXRlY3QgPSAwCgoKc3FsLW1vZGU9Ik5PX0VOR0lORV9TVUJTVElUVVRJT04iCgpbbXlzcWxkdW1wXQpxdWljawpxdW90ZS1uYW1lcwptYXhfYWxsb3dlZF9wYWNrZXQgICAgICA9IDE2TQoKW215c3FsXQoKW2lzYW1jaGtdCmtleV9idWZmZXJfc2l6ZSAgICAgICAgICAgICAgPSAxNk0="
rMySQLCnf = base64.b64decode(eMySQLenc).decode("utf-8")
rConfigPath = "/home/xtreamcodes/iptv_xtream_codes/config"


class col:
    HEADER = "\033[95m"
    OKBLUE = "\033[94m"
    OKGREEN = "\033[92m"
    WARNING = "\033[93m"
    FAIL = "\033[91m"
    ENDC = "\033[0m"
    BOLD = "\033[1m"
    UNDERLINE = "\033[4m"
    CYAN = "\033[96m"
    MAGENTA = "\033[95m"
    GRAY = "\033[90m"


def generate(length=19):
    return "".join(random.choice(string.ascii_letters + string.digits) for i in range(length))


def getIP():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    return s.getsockname()[0]


def getVersion():
    try:
        return subprocess.check_output("lsb_release -d".split()).split(":")[-1].strip()
    except:
        return ""

# Okvir sa tekstovima
def printc(rText, rColour=col.OKBLUE, rPadding=0):
    # Određivanje širine okvira
    box_width = 60
    title = " Infinity AI Panel "
    
    # Gornja granica okvira
    dash_len = (box_width - 2 - len(title)) // 2
    top_line = f"{rColour}┌{'─' * dash_len}{title}{'─' * dash_len}─┐{col.ENDC}"
    
    # Tekstualna linija sa centriranim tekstom
    text_padding = (box_width - 2 - len(rText)) // 2
    text_line = f"{rColour}│{' ' * text_padding}{rText}{' ' * (box_width - 2 - len(rText) - text_padding)}│{col.ENDC}"
    
    # Donja granica okvira
    bottom_line = f"{rColour}└{'─' * (box_width - 2)}┘{col.ENDC}"
    
    # Prazne linije za vertikalni padding
    empty_line = f"{rColour}│{' ' * (box_width - 2)}│{col.ENDC}"

    # Ispis svih elemenata
    print(top_line)
    for _ in range(rPadding):
        print(empty_line)
    print(text_line)
    for _ in range(rPadding):
        print(empty_line)
    print(bottom_line)
    print(" ")


def prepare(rType="MAIN"):
    global rPackages
    if rType != "MAIN":
        rPackages = rPackages[:-1]
    
    printc("Preparing Installation")
    
    # Backup config file ako postoji
    if os.path.isfile("/home/xtreamcodes/iptv_xtream_codes/config"):
        shutil.copyfile("/home/xtreamcodes/iptv_xtream_codes/config", "/tmp/config.xtmp")
    
    # Ukloni nepotrebne lock file-ove
    lock_files = [
        "/var/lib/dpkg/lock-frontend",
        "/var/cache/apt/archives/lock",
        "/var/lib/dpkg/lock"
    ]
    for lock_file in lock_files:
        try:
            os.remove(lock_file)
        except:
            pass
    
    # System upgrade
    os.system("apt-get update >/dev/null")
    os.system("apt-get -y full-upgrade > /dev/null")
    
    # MariaDB instalacija samo za MAIN
    if rType == "MAIN":
        printc("Installing MariaDB Server 11.8.1")
        os.system("apt-get install software-properties-common -y >/dev/null")
        os.system("apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xF1656F24C74CD1D8 >/dev/null 2>&1")
        os.system("add-apt-repository 'deb [arch=amd64,arm64,ppc64el] http://ams2.mirrors.digitalocean.com/mariadb/repo/11.8.1/ubuntu focal main' >/dev/null")
        os.system("apt-get update >/dev/null")
    
    # Instalacija paketa
    for package in rPackages:
        printc(f"Installing {package}")
        os.system(f"apt-get install {package} -y > /dev/null 2>&1")
    
    # Python dependencies
    printc("Installing pip2 and python2 paramiko")
    os.system("apt-get install curl -y >/dev/null")
    os.system("add-apt-repository universe >/dev/null 2>&1")
    os.system("curl http://sehara.eu:5656/Infinity/get-pip.py --output get-pip.py >/dev/null 2>&1")
    os.system("pip2 install paramiko >/dev/null 2>&1 && rm -rf get-pip.py")
    
    # Libssl i libpng
    os.system('echo "deb http://security.ubuntu.com/ubuntu xenial-security main" | tee -a /etc/apt/sources.list >/dev/null')
    os.system("apt-get update >/dev/null && apt-get install -y libssl1.0.0 >/dev/null")
    os.system("add-apt-repository ppa:linuxuprising/libpng12 -y > /dev/null 2>&1")
    os.system("apt-get update > /dev/null 2>&1 && apt-get install libpng12-0 -y > /dev/null 2>&1")
    os.system("apt-get install -f > /dev/null 2>&1")
    
    # Libcurl fix
    os.system("cp /usr/lib/x86_64-linux-gnu/libcurl.so.4 /usr/lib/ > /dev/null 2>&1")
    os.system("env LD_PRELOAD=/usr/lib/libcurl.so.4 > /dev/null 2>&1")
    os.system("apt-get remove --auto-remove libcurl4-openssl-dev -y > /dev/null 2>&1")
    os.system("apt-get install libcurl3 -y > /dev/null 2>&1")
    
    # Čišćenje
    try:
        os.remove("/tmp/libpng12.deb")
    except:
        pass
    
    # Kreiranje korisnika
    try:
        subprocess.check_output("getent passwd xtreamcodes > /dev/null".split())
    except:
        printc("Creating user")
        os.system("adduser --system --shell /bin/false --group --disabled-login xtreamcodes > /dev/null")
    
    # Kreiranje home direktorija
    if not os.path.exists("/home/xtreamcodes"):
        os.mkdir("/home/xtreamcodes")
    
    return True


def install(rType="MAIN"):
    global rInstall, rDownloadURL
    printc("Downloading Software")
    try:
        rURL = rDownloadURL[rInstall[rType]]
    except:
        printc("Invalid download URL!", col.FAIL)
        return False
    os.system('wget -q -O "/tmp/xtreamcodes.tar.gz" "%s"' % rURL)
    if os.path.exists("/tmp/xtreamcodes.tar.gz"):
        printc("Installing Software")
        os.system('tar -zxvf "/tmp/xtreamcodes.tar.gz" -C "/home/xtreamcodes/" > /dev/null')
        try:
            os.remove("/tmp/xtreamcodes.tar.gz")
        except:

            pass
        return True
    printc("Failed to download installation file!", col.FAIL)
    return False


def mysql(rUsername, rPassword):
    global rMySQLCnf
    printc("Configuring MariaDB- wait maybe slowly")
    rCreate = True
    if os.path.exists("/etc/mysql/my.cnf"):
        if open("/etc/mysql/my.cnf", "r").read(14) == "# Xtream Codes":
            rCreate = False
    if rCreate:
        shutil.copy("/etc/mysql/my.cnf", "/etc/mysql/my.cnf.xc")
        rFile = open("/etc/mysql/my.cnf", "w")
        rFile.write(rMySQLCnf)
        rFile.close()
        os.system("systemctl restart mariadb > /dev/null")
    # printc("Enter MySQL Root Password:", col.WARNING)
    for i in range(5):
        rMySQLRoot = ""  # raw_input("  ")
        print(" ")

        if len(rMySQLRoot) > 0:
            rExtra = " -p%s" % rMySQLRoot

        else:
            rExtra = ""
        printc("Drop existing & create database? Y/N", col.WARNING)
        if input("  ").upper() == "Y":
            rDrop = True

        else:
            rDrop = False
        try:
            if rDrop:
                os.system('mariadb -u root%s -e "DROP DATABASE IF EXISTS xtream_iptvpro; CREATE DATABASE IF NOT EXISTS xtream_iptvpro;" 2> /dev/null' % rExtra)
                os.system('mariadb -u root%s -e "DROP DATABASE IF EXISTS infinity_migrate; CREATE DATABASE IF NOT EXISTS infinity_migrate;" > /dev/null' % rExtra)
                os.system("mariadb -u root%s -e \"USE xtream_iptvpro; DROP USER IF EXISTS '%s'@'%%';\" > /dev/null" % (rExtra, rUsername))
                os.system("mariadb -u root%s xtream_iptvpro < /home/xtreamcodes/iptv_xtream_codes/database.sql 2> /dev/null" % rExtra)

                os.system("mariadb -u root%s -e \"USE xtream_iptvpro; UPDATE settings SET live_streaming_pass = '%s', unique_id = '%s', crypt_load_balancing = '%s';\" 2> /dev/null" % (rExtra, generate(20), generate(10), generate(20)))
                os.system("mariadb -u root%s -e \"USE xtream_iptvpro; REPLACE INTO streaming_servers (id, server_name, domain_name, server_ip, vpn_ip, ssh_password, ssh_port, diff_time_main, http_broadcast_port, total_clients, system_os, network_interface, latency, status, enable_geoip, geoip_countries, last_check_ago, can_delete, server_hardware, total_services, persistent_connections, rtmp_port, geoip_type, isp_names, isp_type, enable_isp, boost_fpm, http_ports_add, network_guaranteed_speed, https_broadcast_port, https_ports_add, whitelist_ips, watchdog_data, timeshift_only) VALUES (1, 'Main Server', '', '%s', '', NULL, NULL, 0, 8080, 1000, '%s', 'eth0', 0, 1, 0, '', 0, 0, '{}', 3, 0, 25462, 'low_priority', '', 'low_priority', 0, 1, '', 1000, 8443, '', '[\"127.0.0.1\",\"\"]', '{}', 0);\" 2> /dev/null" % (rExtra, getIP(), getVersion()))
                os.system("mariadb -u root%s -e \"USE xtream_iptvpro; REPLACE INTO reg_users (id, username, password, email, member_group_id, verified, status) VALUES (1, 'admin', '\$6\$rounds=20000\$xtreamcodes\$XThC5OwfuS0YwS4ahiifzF14vkGbGsFF1w7ETL4sRRC5sOrAWCjWvQJDromZUQoQuwbAXAFdX3h3Cp3vqulpS0', 'admin@website.com', 1, 1, 1);\" 2> /dev/null" % rExtra)
                os.system("mariadb -u root%s -e \"CREATE USER '%s'@'%%' IDENTIFIED BY '%s'; GRANT ALL PRIVILEGES ON xtream_iptvpro.* TO '%s'@'%%' WITH GRANT OPTION; GRANT SELECT, LOCK TABLES ON *.* TO '%s'@'%%';FLUSH PRIVILEGES;\" > /dev/null" % (rExtra, rUsername, rPassword, rUsername, rUsername))
                os.system("mariadb -u root%s -e \"USE xtream_iptvpro; CREATE TABLE IF NOT EXISTS dashboard_statistics (id int(11) NOT NULL AUTO_INCREMENT, type varchar(16) NOT NULL DEFAULT '', time int(16) NOT NULL DEFAULT '0', count int(16) NOT NULL DEFAULT '0', PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO dashboard_statistics (type, time, count) VALUES('conns', UNIX_TIMESTAMP(), 0),('users', UNIX_TIMESTAMP(), 0);\" > /dev/null" % rExtra)
            try:
                os.remove("/home/xtreamcodes/iptv_xtream_codes/database.sql")
            except:
                pass
            return True
        except:
            printc("Invalid password! Try again", col.FAIL)
    return False


def encrypt(
    rHost="127.0.0.1",
    rUsername="user_iptvpro",
    rPassword="",
    rDatabase="xtream_iptvpro",
    rServerID=1,
    rPort=7999,
):

    printc("Encrypting...")
    # config ok

    with open(rConfigPath, "wb") as rf:
        data = "".join(
            chr(ord(c) ^ ord(k))
            for c, k in zip(
                '{"host":"%s","db_user":"%s","db_pass":"%s","db_name":"%s","server_id":"%d", "db_port":"%d"}' % (rHost, rUsername, rPassword, rDatabase, rServerID, rPort),
                cycle("92e7c62a83b9f1d2560b4d5fa3c8a1e4"),
            )
        )
        encoded_data = base64.b64encode(data.encode()).decode().replace("\n", "")
        rf.write(encoded_data.encode())


def configure():
    printc("Configuring System")
    if not "/home/xtreamcodes/iptv_xtream_codes/" in open("/etc/fstab").read():
        rFile = open("/etc/fstab", "a")
        rFile.write("tmpfs /home/xtreamcodes/iptv_xtream_codes/streams tmpfs defaults,noatime,nosuid,nodev,noexec,mode=1777,size=90% 0 0\ntmpfs /home/xtreamcodes/iptv_xtream_codes/tmp tmpfs defaults,noatime,nosuid,nodev,noexec,mode=1777,size=2G 0 0")
        rFile.close()
    if not "xtreamcodes" in open("/etc/sudoers").read():
        os.system('echo "xtreamcodes ALL=(root) NOPASSWD: /sbin/iptables, /usr/bin/chattr, /usr/bin/python2, /usr/bin/python, /home/xtreamcodes/iptv_xtream_codes/nginx.sh" >> /etc/sudoers')
    if not os.path.exists("/etc/init.d/xtreamcodes"):
        rStart = open("/etc/init.d/xtreamcodes", "w")
        rStart.write("#!/bin/bash\n### BEGIN INIT INFO\n# Provides:          xtreamcodes\n# Required-Start:    $all\n# Required-Stop:\n# Default-Start:     2 3 4 5\n# Default-Stop:\n# Short-Description: Run /etc/init.d/xtreamcodes if it exist\n### END INIT INFO\nsleep 1\n/home/xtreamcodes/iptv_xtream_codes/start_services.sh > /dev/null")
        rStart.close()
        os.system("chmod +x /etc/init.d/xtreamcodes")
        os.system("update-rc.d xtreamcodes defaults")
        # os.system("update-rc.d xtreamcodes enable")
        os.system("/lib/systemd/systemd-sysv-install enable xtreamcodes")
    try:
        os.remove("/usr/bin/ffmpeg")
    except:
        pass
    if not os.path.exists("/home/xtreamcodes/iptv_xtream_codes/tv_archive"):
        os.mkdir("/home/xtreamcodes/iptv_xtream_codes/tv_archive/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/assets /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/data /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/emoticons /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/icons /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/inc /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/lang /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/monitor /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/standalone /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/uploads /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/vendor /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/veno-file-manager /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/images /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/layout /home/xtreamcodes/iptv_xtream_codes/reseller/")
    os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/admin/reseller /home/xtreamcodes/iptv_xtream_codes/reseller/")
    # Provjera za ffmpeg
    if not os.path.exists("/usr/bin/ffmpeg"):
        os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/bin/ffmpeg /usr/bin/")
    # Provjera za ffprobe
    if not os.path.exists("/usr/bin/ffprobe"):
        os.system("ln -s /home/xtreamcodes/iptv_xtream_codes/bin/ffprobe /usr/bin/")
    os.system("chattr -i /home/xtreamcodes/iptv_xtream_codes/GeoLite2.mmdb > /dev/null")
    os.system("wget -q http://sehara.eu:5656/Infinity/GeoLite2.mmdb -O /home/xtreamcodes/iptv_xtream_codes/GeoLite2.mmdb")
    os.system("wget -q http://sehara.eu:5656/Infinity/pid_monitor.php -O /home/xtreamcodes/iptv_xtream_codes/crons/pid_monitor.php")
    os.system("chown xtreamcodes:xtreamcodes -R /home/xtreamcodes > /dev/null")
    os.system("chmod -R 0777 /home/xtreamcodes > /dev/null")
    #################################### add permissions #####################################################################

    os.system("sudo chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/VaiIb8.pid 2> /dev/null")
    os.system("sudo chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/JdlJXm.pid 2> /dev/null")
    os.system("sudo chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/CWcfSP.pid 2> /dev/null")

    os.system("sudo chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/f3rD1w.pid 2> /dev/null")
    os.system("sudo chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/Rgv8i1.pid 2> /dev/null")
    os.system("sudo chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/rmsC3z.pid 2> /dev/null")
    os.system("chmod +x /home/xtreamcodes/iptv_xtream_codes/start_services.sh > /dev/null")
    os.system("chattr -i /home/xtreamcodes/iptv_xtream_codes/GeoLite2.mmdb > /dev/null")
    os.system("mount -a")
    if not "api.xtream-codes.com" in open("/etc/hosts").read():
        os.system('echo "127.0.0.1    api.xtream-codes.com" >> /etc/hosts')
    if not "downloads.xtream-codes.com" in open("/etc/hosts").read():
        os.system('echo "127.0.0.1    downloads.xtream-codes.com" >> /etc/hosts')
    if not " xtream-codes.com" in open("/etc/hosts").read():
        os.system('echo "127.0.0.1    xtream-codes.com" >> /etc/hosts')
    # INSTALL UPDATe
    # downupdate = linkupdate
    os.system('apt-get install unzip e2fsprogs python-paramiko -y >/dev/null && chattr -i /home/xtreamcodes/iptv_xtream_codes/GeoLite2.mmdb >/dev/null && rm -rf /home/xtreamcodes/iptv_xtream_codes/admin 2>/dev/null && rm -rf /home/xtreamcodes/iptv_xtream_codes/pytools 2>/dev/null && wget -O /tmp/update.zip "http://sehara.eu:5656/Infinity/update.zip" 2>/dev/null && unzip /tmp/update.zip -d /tmp/update/ >/dev/null && cp -rf /tmp/update/XtreamUI-master/* /home/xtreamcodes/iptv_xtream_codes/ >/dev/null && rm -rf /tmp/update/XtreamUI-master >/dev/null && rm /tmp/update.zip >/dev/null && rm -rf /tmp/update >/dev/null && chown -R xtreamcodes:xtreamcodes /home/xtreamcodes/ >/dev/null && chmod +x /home/xtreamcodes/iptv_xtream_codes/permissions.sh >/dev/null && /home/xtreamcodes/iptv_xtream_codes/permissions.sh >/dev/null && find /home/xtreamcodes/ -type d -not \( -name .update -prune \) -exec chmod -R 777 {} + >/dev/null')
    os.system('sed -i \'s|echo "Infinity AI ";|header("Location: https://www.google.com/");|g\' /home/xtreamcodes/iptv_xtream_codes/wwwdir/index.php')

    printc("Install Youtube Module")
    os.system("sudo -H PYTHONWARNINGS='ignore' pip install --upgrade youtube-dl > /dev/null && wget -O /usr/local/bin/youtube_dl.zip 'http://sehara.eu:5656/Infinity/youtube-dl.zip' 2> /dev/null && sudo unzip -o /usr/local/bin/youtube_dl.zip -d /usr/local/bin/ > /dev/null && wget -O /usr/local/bin/youtube_dl.zip 'http://sehara.eu:5656/Infinity/youtube-dl.zip' 2> /dev/null && sudo unzip -o /usr/local/bin/youtube_dl.zip -d /usr/local/bin/ > /dev/null && rm -rf youtube*.zip > /dev/null && sudo chmod a+rx /usr/local/bin/youtube-dl")

    # UPDATE NGINX
    printc("Update NGINX")
    os.system("wget http://infinity-panel.pro/archive/addons/UpdateNginxInfinity.zip -P /tmp 2> /dev/null && cd /tmp && unzip UpdateNginxInfinity.zip >/dev/null && mv nginx /home/xtreamcodes/iptv_xtream_codes/nginx/sbin && chmod 777 /home/xtreamcodes/iptv_xtream_codes/nginx/sbin/nginx && chown -R xtreamcodes:xtreamcodes /home/xtreamcodes/iptv_xtream_codes/nginx/sbin/nginx && rm -rf /tmp/UpdateNginxInfinity.zip && /home/xtreamcodes/iptv_xtream_codes/start_services.sh")

    # configuring Cron to restart after reboot
    printc("Configuring cron")
    os.system("echo '@reboot root /home/xtreamcodes/iptv_xtream_codes/start_services.sh' | sudo tee -a /etc/crontab > /dev/null 2>&1")


def start(first=True):
    if first:
        printc("Starting Infinity AI")

        # changing permission for pid
        os.system('sudo sed -i "1i chattr -i /home/xtreamcodes/iptv_xtream_codes/GeoLite2.mmdb" /home/xtreamcodes/iptv_xtream_codes/permissions.sh')
        os.system("echo chmod -R 0777 /home/xtreamcodes >> /home/xtreamcodes/iptv_xtream_codes/permissions.sh > /dev/null")
        os.system("echo chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/VaiIb8.pid >> /home/xtreamcodes/iptv_xtream_codes/permissions.sh > /dev/null")
        os.system("echo chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/JdlJXm.pid >> /home/xtreamcodes/iptv_xtream_codes/permissions.sh > /dev/null")
        os.system("echo chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/CWcfSP.pid >> /home/xtreamcodes/iptv_xtream_codes/permissions.sh > /dev/null")
        # checking and runing permissions
        os.system("chmod +x /home/xtreamcodes/iptv_xtream_codes/permissions.sh >/dev/null")
        os.system("/home/xtreamcodes/iptv_xtream_codes/permissions.sh >/dev/null")
        os.system("/home/xtreamcodes/iptv_xtream_codes/permissions.sh >/dev/null")
        os.system("chmod -R 0777 /home/xtreamcodes > /dev/null")
        os.system("chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/VaiIb8.pid >/dev/null")
        os.system("chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/JdlJXm.pid >/dev/null")
        os.system("chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/CWcfSP.pid >/dev/null")
        # default first start

        os.system("/home/xtreamcodes/iptv_xtream_codes/start_services.sh 2>/dev/null")
        os.system("chattr +i /home/xtreamcodes/iptv_xtream_codes/GeoLite2.mmdb")
        os.system("rm -rf get-pip.py")

    else:
        printc("Restarting Infinity AI")
        # changing permission for pid
        os.system('sudo sed -i "1i chattr -i /home/xtreamcodes/iptv_xtream_codes/GeoLite2.mmdb" /home/xtreamcodes/iptv_xtream_codes/permissions.sh')
        os.system("echo \chmod -R 0777 /home/xtreamcodes >> /home/xtreamcodes/iptv_xtream_codes/permissions.sh > /dev/null")
        os.system("echo \chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/VaiIb8.pid >> /home/xtreamcodes/iptv_xtream_codes/permissions.sh > /dev/null")
        os.system("echo \chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/JdlJXm.pid >> /home/xtreamcodes/iptv_xtream_codes/permissions.sh > /dev/null")
        os.system("echo \chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/CWcfSP.pid >> /home/xtreamcodes/iptv_xtream_codes/permissions.sh > /dev/null")
        # checking and runing permissions
        os.system("chmod +x /home/xtreamcodes/iptv_xtream_codes/permissions.sh >/dev/null")
        os.system("/home/xtreamcodes/iptv_xtream_codes/permissions.sh >/dev/null")
        # os.system('/home/xtreamcodes/iptv_xtream_codes/permissions.sh >/dev/null')
        os.system("chmod -R 0777 /home/xtreamcodes > /dev/null")
        os.system("chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/VaiIb8.pid >/dev/null")
        os.system("chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/JdlJXm.pid >/dev/null")
        os.system("chmod o-w /home/xtreamcodes/iptv_xtream_codes/php/CWcfSP.pid >/dev/null")
        # default first start

        os.system("/home/xtreamcodes/iptv_xtream_codes/start_services.sh 2>/dev/null")
        os.system("chattr +i /home/xtreamcodes/iptv_xtream_codes/GeoLite2.mmdb")
        os.system("rm -rf get-pip.py")


if __name__ == "__main__":

    printc("For Ubuntu 20 with MariaDB", col.OKGREEN, 2)
    try:
        rType = input("  INSTALLATION TYPE [MAIN, LB]: ")
    except KeyboardInterrupt:
        print("\nExiting..")
        sys.exit(0)

    # rType = input("  INSTALLATION TYPE [MAIN, LB]: ")
    print(" ")
    if rType.upper() in ["MAIN", "LB"]:
        if rType.upper() == "LB":
            rHost = input("  Main Server IP Address: ")
            rPassword = input("  MySQL Password: ")
            try:
                rServerID = int(input("  Load Balancer Server ID: "))
            except:
                rServerID = -1
            print(" ")
        else:
            rHost = "127.0.0.1"
            rPassword = generate(18)
            rServerID = 1
            rAccesscode = generate(12)
            rExtra = ""
        rUsername = "user_iptvpro"
        rDatabase = "xtream_iptvpro"
        rPort = 7999
        if len(rHost) > 0 and len(rPassword) > 0 and rServerID > -1:
            printc("START INSTALLATION? Y/N", col.WARNING)
            if input("  ").upper() == "Y":
                print(" ")
                rRet = prepare(rType.upper())
                if not install(rType.upper()):
                    sys.exit(1)
                if rType.upper() == "MAIN":
                    if not mysql(rUsername, rPassword):
                        sys.exit(1)

                if rType.upper() == "MAIN":
                    os.system("sed -i 's|randomcodehere|%s|g' /home/xtreamcodes/iptv_xtream_codes/nginx/conf/codes/panel/admin_panel.conf" % rAccesscode)
                    os.system("mariadb -u root%s -e \"USE xtream_iptvpro; UPDATE access_codes SET code = '%s' WHERE id = 1;\" > /dev/null" % (rExtra, rAccesscode))
                    os.system("/home/xtreamcodes/iptv_xtream_codes/start_services.sh > /dev/null")
                encrypt(rHost, rUsername, rPassword, rDatabase, rServerID, rPort)
                configure()

                start()
                printc("Infinity AI INSTALLATION COMPLETED!", col.OKGREEN, 2)

                if rType.upper() == "MAIN":
                    printc("Please store your MySQL password!")
                    printc(rPassword)
                    printc("http://%s/%s" % (getIP(), rAccesscode))
                    printc("Infinity default login is admin/admin")
            else:
                printc("Installation cancelled", col.FAIL)
        else:
            printc("Invalid entries", col.FAIL)
    else:
        printc("Invalid installation type", col.FAIL)
