#copyright(c)Syslint technologies
import os
from shellcolor import shellcolor
from datetime import datetime
import subprocess
import version
import deps
import sys
import pre
import time
import shutil

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

def start():
    now = datetime.now()
    sys.stdout.write("Copyright (C) 2009-"+str(now.year)+", Syslint Technologies India(P) LTD.")
    sys.stdout.write("""
                            _                                       
  ___  _ __   _ __    __ _ (_) _ __  __  __    ___  ___   _ __ ___  
 / __|| '_ \ | '_ \  / _` || || '_ \ \ \/ /   / __|/ _ \ | '_ ` _ \ 
| (__ | |_) || | | || (_| || || | | | >  <  _| (__| (_) || | | | | |
 \___|| .__/ |_| |_| \__, ||_||_| |_|/_/\_\(_)\___|\___/ |_| |_| |_|
      |_|            |___/                                          
        
        """)
    sys.stdout.write("\n")
    with open('/etc/cpnginx/version','r') as lo:
        old_version=lo.read().strip()
    pwd=os.getcwd()
    with open(pwd+"/setup/src/etc/cpnginx/version",'r') as nw:
        new_version=nw.read().strip()
    very_old=old_version.split('.')[0]
    if old_version == new_version:
        sys.stdout.write("This server is runing the same version of cpnignx software .. "+shellcolor.green+new_version+shellcolor.end+"\n")
        sys.stdout.write("If you are looking for reinstall, please remove the current installation.\n")
        sys.stdout.write("Upgrade "+shellcolor.fail+"failed"+shellcolor.end+" .. reason .. same versions\n")
        sys.exit(0)
    elif very_old == "10":
        sys.stdout.write("This server is running a depretiated  cpnginx version .. "+old_version+"\n")
        sys.stdout.write("Your current Cpnginx will be removed from the server\n")
        bkptime=str(time.mktime(now.timetuple()))
        sys.stdout.write("Before  starting the upgrade we will  take a  backup for your current cpnginx\n")
        sys.stdout.write("settings into the folder /opt/cpnginx/"+bkptime+"\n")        
        sys.stdout.write("This auto upgrade will start within 20 seconds, if you don't need to proceed press CTRL+C ..\n")
        time.sleep(20)
        deps.install_deps()
        deps.install_python()
        src='/opt/cpnginx'
        backupath=src+'/'+bkptime
        sys.stdout.write("Creating backup  folder .. "+backupath+"\n")
        if not os.path.exists(backupath):
            os.makedirs(backupath)
        sys.stdout.write("Copying /etc/cpnginx  ")
        cp1='cp -arf /etc/cpnginx '+backupath+'/'
        subprocess.call(cp1,shell=True)
        sys.stdout.write(".. done\n")
        sys.stdout.write("Copying /usr/local/nginx/conf .. ")
        cp2='cp -arf /usr/local/nginx/conf '+backupath+'/'
        subprocess.call(cp2,shell=True)
        sys.stdout.write(".. done\n")
        sys.stdout.write("Now removing the old installation")
        deps.remove_hooks()
        deps.clean_fpm()
        deps.remove_disable()
        deps.remove_files()
        sys.stdout.write("Installing new Cpnginx version \n")
        deps.copy_core()
        deps.ea4_enable_mod_remoteip()
        deps.ea4_default_php_fpm()
        deps.change_apache_port()
        deps.install_nginx()
        deps.install_hooks()
        deps.install_whm_plugin()
        deps.install_cpanel_plugin()
        deps.install_hooks()
        deps.install_cron()
        deps.setup_templates()
        deps.setup_chkservd()
        deps.restart_services()
        sys.stdout.write("""

..................................................................

Cpnginx Upgrade has been completed  No you may do the following,

- Install the nginx modsecurity rules using the command #nginxctl
- Set the fpm php.ini values from WHM -> Cpnginx

..................................................................
        """)
        sys.stdout.write("\n")
    else:
        sys.stdout.write("Upgrading cpnginx to the new  version .. "+shellcolor.green+new_version+shellcolor.end+"\n")
        deps.remove_hooks()
        deps.install_deps()
        deps.upgrade_core()
        deps.install_cron()
        deps.upgrade_whm_plugin()
        deps.upgrade_cpanel_plugin()
        deps.install_hooks()
        deps.setup_templates()
        rebuild_all_vhost()
        deps.restart_services()
        sys.stdout.write("---------------------------------------------------------------------------------\n")
        sys.stdout.write("\t\t Cpnginx upgrade has been completed \n")
        sys.stdout.write("\tPlease refer the documentation from https://cpnginx.com to getting start\n ")
        sys.stdout.write("---------------------------------------------------------------------------------\n")
        sys.exit(0)
