import sys
import subprocess
import os
from shellcolor import shellcolor
import platform
import dataparse

def check_cp_version():
    vfile="/usr/local/cpanel/version" 
    if os.path.exists(vfile):
        ver=open(vfile,'r')
        version=ver.read().strip()
        current= '.'.join(version.split(".", 2)[:2])
        if float(current) < float('11.76'):
            return 'old'
        else:
            return 'new'
    else:
        return 'new'

def find_ea_version():
	command=['/usr/local/cpanel/scripts/easyapache --version']
	DEVNULL = open(os.devnull, 'wb')
	proc=subprocess.Popen(command,stdout=DEVNULL,stderr=DEVNULL,shell=True)
	(output, err) = proc.communicate()
	p_status = proc.wait()
	
	if p_status > 0 :
		ea=4	
	else:
		ea=4
	return ea

def get_this_version():
    vfile="setup/src/etc/cpnginx/version" 
    if os.path.exists(vfile):
        ver=open(vfile,'r')
        version=ver.read().strip()
        return version
    else:
        version="unknown"
        return version

def check_cpphp_ioncube():
    command=['/usr/local/cpanel/3rdparty/bin/php -v | grep ionCube']
    DEVNULL = open(os.devnull, 'wb')
    proc=subprocess.Popen(command,stdout=DEVNULL,stderr=DEVNULL,shell=True)
    (output, err) = proc.communicate()
    p_status = proc.wait()
    return p_status

def install_deps():
    sys.stdout.write("Installing dependencies for cpnginx ..\n")
    command="yum -y install readline-devel bzip2-devel xz-devel sqlite-devel tkinter libffi-devel zlib-devel pcre-devel openssl-devel GeoIP-devel yara-devel flex-devel bison-devel"
    subprocess.call(command,shell=True)
def install_python():
    pwd= os.getcwd()
    pyinstall=pwd+'/setup/src/scripts/cpnginx/buildpython.sh'
    cmd='sh '+pyinstall+' --install'
    subprocess.call(cmd,shell=True)


def upgrade_core():
    sys.stdout.write("Copying core files .. ")
    pwd=os.getcwd()
    sys.stdout.write("Copying   cpnginx files to /etc/ ... \n")
    cmd_etc1="/bin/cp -arf "+pwd+"/setup/src/etc/cpnginx/build /etc/cpnginx/"
    cmd_etc2="/bin/cp -arf "+pwd+"/setup/src/etc/cpnginx/templates /etc/cpnginx/"
    cmd_etc3="/bin/cp -arf "+pwd+"/setup/src/etc/cpnginx/updatecpnginx.py /etc/cpnginx/"
    cmd_etc4="/bin/cp -arf "+pwd+"/setup/src/etc/cpnginx/version /etc/cpnginx/"
    subprocess.call(cmd_etc1,shell=True)
    subprocess.call(cmd_etc2,shell=True)
    subprocess.call(cmd_etc3,shell=True)
    subprocess.call(cmd_etc4,shell=True)
    sys.stdout.write(shellcolor.green+"done"+shellcolor.end+"\n")
    sys.stdout.write("Copying cpnginx core to /scripts/ .. ")
    cmd_script="/bin/cp -arf "+pwd+"/setup/src/scripts/* /usr/local/cpanel/scripts/"
    cmd_ctl="ln -sf /usr/local/cpanel/scripts/nginxctl /usr/bin/nginxctl"
    subprocess.call(cmd_script,shell=True)
    subprocess.call(cmd_ctl,shell=True)
    os.chmod('/usr/local/cpanel/scripts/nginxctl',0750)
    sys.stdout.write(shellcolor.green+"done"+shellcolor.end+"\n")

def copy_core():
    sys.stdout.write("Copying core files\n")
    pwd=os.getcwd()
    cmd_etc="/bin/cp -arf "+pwd+"/setup/src/etc/cpnginx /etc/"
    cmd_script="/bin/cp -arf "+pwd+"/setup/src/scripts/* /usr/local/cpanel/scripts/"
    cmd_ctl="ln -sf /usr/local/cpanel/scripts/nginxctl /usr/bin/nginxctl"
    sys.stdout.write("Copying   cpgninx files to /etc/ ... ")
    subprocess.call(cmd_etc,shell=True)
    sys.stdout.write(shellcolor.green+"done"+shellcolor.end+"\n")
    sys.stdout.write("Copying cpnginx core to /scripts/ ..")
    subprocess.call(cmd_script,shell=True)
    subprocess.call(cmd_ctl,shell=True)
    os.chmod('/usr/local/cpanel/scripts/nginxctl',0750)
    sys.stdout.write(shellcolor.green+"done"+shellcolor.end+"\n")




def ea4_enable_mod_remoteip():
    subprocess.call(['/usr/local/cpanel/scripts/nginxctl  build remoteip'],shell=True)

def install_cron():
    sys.stdout.write("Installing SSL Monitoring cron  .. \n")
    cmd='/bin/cp -af /etc/cpnginx/cpnginx-cron /etc/cron.d/'
    subprocess.call(cmd,shell=True)


def ea4_default_php_fpm():
    subprocess.call(['/usr/local/cpanel/scripts/nginxctl  setupphpfpm'],shell=True)



def change_apache_port():
    dfile="/etc/cpnginx/data/settings.json"
    http_port=dataparse.readjsonval(dfile,"APACHE_HTTP_PORT")[0]
    https_port=dataparse.readjsonval(dfile,"APACHE_HTTPS_PORT")[0]
    cmdhttp='sed -i s/apache_port.*/apache_port=0.0.0.0:'+http_port+'/g /var/cpanel/cpanel.config'
    cmdhttps='sed -i s/apache_ssl_port.*/apache_ssl_port=0.0.0.0:'+https_port+'/g /var/cpanel/cpanel.config'
    subprocess.call(cmdhttp,shell=True)
    subprocess.call(cmdhttps,shell=True)
    subprocess.call(['/usr/local/cpanel/scripts/rebuildhttpdconf'],shell=True)
    subprocess.call(['/usr/local/cpanel/scripts/restartsrv_httpd'],shell=True)

def install_nginx():
    subprocess.call(['/usr/local/cpanel/scripts/nginxctl nginxbuild --enable-modsec'],shell=True)

def upgrade_whm_plugin():
    sys.stdout.write("...............................................................................\n")
    sys.stdout.write("\t \tUpgrading WHM  Cpnginx Administration Panel   \n")
    sys.stdout.write("...............................................................................\n")
    sys.stdout.write("Starting installation of whm plugin files .. "+shellcolor.green+"start"+shellcolor.end+"\n")
    if not os.path.exists("/var/cpanel/apps"):
        subprocess.call(['mkdir -pv /var/cpanel/apps && chmod 750 /var/cpanel/apps'],shell=True)
    appremove="/usr/local/cpanel/bin/unregister_appconfig cpnginx"
    subprocess.call(appremove,shell=True)
    pwd=os.getcwd()
    appcfg= pwd+"/setup/src/whm/cpnginx.conf"
    appinstall="/usr/local/cpanel/bin/register_appconfig "+appcfg
    subprocess.call(appinstall,shell=True)
    appfilecmd="/bin/cp -arf "+pwd+"/setup/src/whm/cpnginx /usr/local/cpanel/whostmgr/cgi/"
    subprocess.call(appfilecmd,shell=True)
    cpicon="/bin/cp -af /usr/local/cpanel/whostmgr/cgi/cpnginx/ico-cpnginx.png  /usr/local/cpanel/whostmgr/docroot/addon_plugins/"
    subprocess.call(cpicon,shell=True)
    sys.stdout.write("Finishing installation of whm plugins files .. "+shellcolor.green+"done"+shellcolor.end+"\n")


def install_whm_plugin():
    sys.stdout.write("...............................................................................\n")
    sys.stdout.write("\t \tInstalling WHM  Cpnginx Administration Panel   \n")
    sys.stdout.write("...............................................................................\n")
    sys.stdout.write("Starting installation of whm plugin files .. "+shellcolor.green+"start"+shellcolor.end+"\n")
    if not os.path.exists("/var/cpanel/apps"):
        subprocess.call(['mkdir -pv /var/cpanel/apps && chmod 750 /var/cpanel/apps'],shell=True)
    pwd=os.getcwd()
    appcfg= pwd+"/setup/src/whm/cpnginx.conf"
    appinstall="/usr/local/cpanel/bin/register_appconfig "+appcfg
    subprocess.call(appinstall,shell=True)
    appfilecmd="/bin/cp -arf "+pwd+"/setup/src/whm/cpnginx /usr/local/cpanel/whostmgr/cgi/"
    subprocess.call(appfilecmd,shell=True)
    cpicon="/bin/cp -af /usr/local/cpanel/whostmgr/cgi/cpnginx/ico-cpnginx.png  /usr/local/cpanel/whostmgr/docroot/addon_plugins/"
    subprocess.call(cpicon,shell=True)
    sys.stdout.write("Finishing installation of whm plugins files .. "+shellcolor.green+"done"+shellcolor.end+"\n")

def upgrade_cpanel_plugin():
    sys.stdout.write("..............................................................................\n")
    sys.stdout.write("\t \tInstalling cPanel Nginx Plugin   \n")
    sys.stdout.write("...............................................................................\n")
    sys.stdout.write("Starting installation of cpanel plugin files .. "+shellcolor.green+"start"+shellcolor.end+"\n")
    pwd=os.getcwd()
    cpnaelplugin=pwd+"/setup/src/cpanel/cpnginx.tar.gz"
    rm_cpanel="/usr/local/cpanel/scripts/uninstall_plugin "+cpnaelplugin
    subprocess.call(rm_cpanel,shell=True)
    plug=pwd+"/setup/src/cpanel/cpnginx.tar.gz"
    installplug="/usr/local/cpanel/scripts/install_plugin "+plug
    subprocess.call(installplug,shell=True)
    plgcpy="/bin/cp -arf "+pwd+"/setup/src/cpanel/cpnginx /usr/local/cpanel/base/frontend/paper_lantern/"
    subprocess.call(plgcpy,shell=True)
    sys.stdout.write("Finishing installation of cpanel plugins files .. "+shellcolor.green+"done"+shellcolor.end+"\n")

def install_cpanel_plugin():
    sys.stdout.write("..............................................................................\n")
    sys.stdout.write("\t \tInstalling cPanel Nginx Plugin   \n")
    sys.stdout.write("...............................................................................\n")
    sys.stdout.write("Starting installation of cpanel plugin files .. "+shellcolor.green+"start"+shellcolor.end+"\n")
    pwd=os.getcwd()
    plug=pwd+"/setup/src/cpanel/cpnginx.tar.gz"
    installplug="/usr/local/cpanel/scripts/install_plugin "+plug
    subprocess.call(installplug,shell=True)
    plgcpy="/bin/cp -arf "+pwd+"/setup/src/cpanel/cpnginx /usr/local/cpanel/base/frontend/paper_lantern/"
    subprocess.call(plgcpy,shell=True)
    sys.stdout.write("Finishing installation of cpanel plugins files .. "+shellcolor.green+"done"+shellcolor.end+"\n")

def install_hooks():
    sys.stdout.write("Installing cpnginx hooks ..\n")
    os.chmod('/usr/local/cpanel/scripts/cpnginx/hooks/cpnginxhooks',0755)
    subprocess.call(['/usr/local/cpanel/scripts/cpnginx/hooks/cpnginxhooks install'],shell=True)

def remove_hooks():
    sys.stdout.write("Removing cpnginx hooks ..\n")
    os.chmod('/usr/local/cpanel/scripts/cpnginx/hooks/cpnginxhooks',0755)
    subprocess.call(['/usr/local/cpanel/scripts/cpnginx/hooks/cpnginxhooks remove'],shell=True)

def setup_templates():
    subprocess.call(['/usr/local/cpanel/scripts/nginxctl templaterebuild'],shell=True)

def setup_chkservd():
    if os.path.exists('/etc/chkserv.d/nginx'):
        sys.stdout.write("Nginx Chkservd Configuration file  already exists .. " + shellcolor.green+"ok"+shellcolor.end+"\n")
    else:
        copycmd='cp -f /etc/cpnginx/build/templates/nginx.chkservd /etc/chkserv.d/nginx'
        subprocess.call(copycmd,shell=True)
        rmng=['grep -v nginx /etc/chkserv.d/chkservd.conf > /tmp/chk.conf']
        subprocess.call(rmng,shell=True)
        enablechk=['echo "nginx:1" >> /tmp/chk.conf ']   # need to add as new line 
        subprocess.call(enablechk,shell=True)
        reng=['cat /tmp/chk.conf > /etc/chkserv.d/chkservd.conf']
        subprocess.call(reng,shell=True)
        changeapache=['sed -i s/80/9080/g /etc/chkserv.d/httpd']
        attr=['chattr +ia /etc/chkserv.d/httpd']
        subprocess.call(changeapache,shell=True)
        subprocess.call(attr,shell=True)
        subprocess.call(['/usr/local/cpanel/scripts/restartsrv_chkservd'],shell=True)
        sys.stdout.write("nginx chkservd installed  .. /etc/chkserv.d/nginx .." + shellcolor.green+"ok"+shellcolor.end+"\n")

def restart_services():
    subprocess.call(['/usr/local/cpanel/scripts/restartsrv_httpd'],shell=True)
    cmd='/usr/local/cpanel/scripts/nginxctl restart'
    subprocess.call(cmd,shell=True)
    sys.stdout.write(shellcolor.pink+"Status of nginx and apache"+shellcolor.end+"\n")
    sys.stdout.write(shellcolor.green+"\n")
    subprocess.call(["netstat -pant | egrep -i 'nginx|httpd'"],shell=True)
    sys.stdout.write(shellcolor.end+"\n")


def remove_disable():
    subprocess.call(['/usr/local/cpanel/scripts/nginxctl disable'],shell=True)

def clean_fpm():
    subprocess.call(['/usr/local/cpanel/scripts/nginxctl cleanfpm'],shell=True)

def remove_files():
    pwd=os.getcwd()
    cpnaelplugin=pwd+"/setup/src/cpanel/cpnginx.tar.gz"
    rm_cpanel="/usr/local/cpanel/scripts/uninstall_plugin "+cpnaelplugin
    appinstall="/usr/local/cpanel/bin/unregister_appconfig cpnginx"
    sys.stdout.write("Removing nginx chkservd file /etc/chkserv.d/nginx .. ")
    subprocess.call(['rm -f /etc/chkserv.d/nginx'],shell=True)
    sys.stdout.write(shellcolor.green+"done"+shellcolor.end+"\n")
    sys.stdout.write("Removing nginx from  /usr/local/nginx  .. ")
    subprocess.call(['rm -rf /usr/local/nginx'],shell=True)
    sys.stdout.write(shellcolor.green+"done"+shellcolor.end+"\n")
    sys.stdout.write("Removing cpnginx configurations   /etc/cpnginx  .. ")
    subprocess.call(['rm -rf /etc/cpnginx'],shell=True)
    sys.stdout.write(shellcolor.green+"done"+shellcolor.end+"\n")
    sys.stdout.write("Removing cpnginx scripts   /usr/local/cpanel/scripts/cpnginx  .. ")
    subprocess.call(['rm -rf /usr/local/cpanel/scripts/cpnginx'],shell=True)
    sys.stdout.write(shellcolor.green+"done"+shellcolor.end+"\n")
    sys.stdout.write("Removing nginxctl     .. ")
    subprocess.call(['rm -rf /usr/local/cpanel/scripts/nginxctl'],shell=True)
    subprocess.call(['unlink /usr/bin/nginxctl'],shell=True)
    sys.stdout.write(shellcolor.green+"done"+shellcolor.end+"\n")
    sys.stdout.write("Removing cpnginx cpanel plugin files   .. ")
    subprocess.call(rm_cpanel,shell=True)
    subprocess.call(['rm -rf /usr/local/cpanel/base/frontend/paper_lantern/cpnginx'],shell=True)
    sys.stdout.write(shellcolor.green+"done"+shellcolor.end+"\n")
    sys.stdout.write("Removing cpnginx whm plugin files   .. ")
    subprocess.call(appinstall,shell=True)
    subprocess.call(['rm -rf /usr/local/cpanel/whostmgr/cgi/cpnginx'],shell=True)
    sys.stdout.write(shellcolor.green+"done"+shellcolor.end+"\n")
    sys.stdout.write("......................................................................\n")
    sys.stdout.write("\t Cpnginx uninstallation completed !! \n")
    sys.stdout.write("......................................................................\n")

