#Copyright(c) Syslint.com
import os
import sys
import json
import subprocess
import shutil

def get_user_home(user):
    with open('/etc/passwd') as pfile:
        lines=pfile.read().splitlines()
    for line in lines:
        if line.split(":")[0] == user:
            home=line.split(":")[5]
    return(home)

def get_main_ip():
    ip='127.0.0.1'
    with open('/etc/wwwacct.conf') as sfile:
        lines=sfile.read().splitlines()
    for line in lines:
        data=line.split()
        if data[0] == 'ADDR' and len(data)==2:
            ip=data[1]
    return(ip)

def get_all_ssl_certificates():
    cmd='/usr/sbin/whmapi1 fetch_vhost_ssl_components --outpu=json'
    datas=os.popen(cmd).read()
    result={}
    ssldata={}
    try:
        result=json.loads(datas)
    except Exception as e:
        print((str(e)))
        pass
    if not bool(result['data']):
        print ("SSL information unable to find")
    else:
        for item in result['data']['components']:
            ssldata[item['servername']]={'key': item['key'],'certificate': item['certificate'],'cabundle': item['cabundle']}
    return ssldata



def get_all_php_fpm():
    cmd='/usr/sbin/whmapi1  php_get_handlers --output=json'
    datas=os.popen(cmd).read()
    defaultcmd='/usr/sbin/whmapi1 php_get_system_default_version --output=json'
    datadef=os.popen(defaultcmd).read()
    try:
        dresult=json.loads(datadef)
    except Exception as e:
        print((str(e)))
        pass
    default=0
    default_php=dresult['data']['version']
    result={}
    fpmdata={}
    oldfpmte="""include=/opt/alt/PHPVER/etc/php-fpm.d/*.conf
[global]"""    
    wwwconftem="""[www]
user = nobody
pm = ondemand
pm.max_children = 5
pm.process_idle_timeout = 15
group = nobody
listen = /run/PHPVERSION-fpm.sock
"""
    try:
        result=json.loads(datas)
    except Exception as e:
        print((str(e)))
        pass
    if not  bool(result['data']):
        print ("Unable to read php detaILS")
    else:
        allphp=[]
        data={}
        for item in result['data']['version_handlers']:
            allphp.append(item['version'])
        for i in allphp:
            fpmpath=''
            clipath=''
            fpmconf=''
            fpmconfdir=''
            fpmservice=''
            php=i.split('-')
            if (php[0]=="ea"):
                if i==default_php:
                    default=1
                    installfpm="yum -y install "+default_php+"-php-fpm"
                    subprocess.call(installfpm,shell=True)
                else:
                    default=0
                fpmpath='/opt/cpanel/ea-'+php[1]+'/root/usr/sbin/php-fpm'
                clipath='/opt/cpanel/ea-'+php[1]+'/root/usr/bin/php'
                fpmconf='/opt/cpanel/ea-'+php[1]+'/root/etc/php-fpm.conf'
                fpmconfdir='/opt/cpanel/ea-'+php[1]+'/root/etc/php-fpm.d'
                fpmservice='ea-'+php[1]+'-php-fpm.service'
                if (os.path.exists(fpmpath) and os.path.exists(clipath)):
                    wwwconf=wwwconftem.replace('PHPVERSION',i)
                    confile=open(fpmconfdir+'/www.conf', "wt")
                    confile.write(wwwconf)
                    confile.close()
                    pversion=str(subprocess.check_output([clipath,"-r" ,"echo phpversion();"]),'utf-8')
                    version=pversion.split(".")
                    data[i]=[version[0],version[1],version[2],fpmpath,fpmconf,fpmconfdir,fpmservice,default]

            elif (php[0]=="alt"):
                if i==default_php:
                    default=1
                else:
                    default=0
                fpmpath='/opt/alt/'+php[1]+'/usr/sbin/php-fpm'
                clipath='/opt/alt/'+php[1]+'/usr/bin/php'
                fpmconf='/opt/alt/'+php[1]+'/etc/php-fpm.conf'
                fpmconfdir='/opt/alt/'+php[1]+'/etc/php-fpm.d'
                fpmservice='alt-'+php[1]+'-fpm.service'
                if (os.path.exists(fpmpath) and os.path.exists(clipath)):
                    if ((php[1]=="php54") or (php[1]=="php55") or (php[1]=="php56")):
                        fpmtem=oldfpmte.replace('PHPVER',php[1])
                        ff=open(fpmconf, "wt")
                        ff.write(fpmtem)
                        ff.close()
                    if not (os.path.exists(fpmconf)):
                        shutil.copyfile(fpmconf+'.default', fpmconf)
                    wwwconf=wwwconftem.replace('PHPVERSION',i)
                    confile=open(fpmconfdir+'/www.conf', "wt")
                    confile.write(wwwconf)
                    confile.close()
                    pversion=str(subprocess.check_output([clipath,"-r" ,"echo phpversion();"]),'utf-8')
                    version=pversion.split(".")
                    data[i]=[version[0],version[1],version[2],fpmpath,fpmconf,fpmconfdir,fpmservice,default]
        return(data)
