import os
import subprocess
from shellcolor import shellcolor
import conf
import json
import cpanel
import dataparse


def ea4_default_php_fpm():
    data=cpanel.get_all_php_fpm()
    for php in data:
        fpmservice=data[php][6]
        enable_service="systemctl enable "+fpmservice
        subprocess.call(enable_service,shell=True)
        print (shellcolor.pink+"Starting php fpm  service version .. "+shellcolor.end+shellcolor.yellow+php+shellcolor.end)
        startfpm="systemctl restart "+fpmservice+" && systemctl status "+fpmservice
        subprocess.call(startfpm,shell=True)
    return data


def reloadfpm(fpm):
    fpmdb=dataparse.readjson("/etc/cpnginx/data/fpm.json")
    service=fpmdb[fpm][6]
    cmd="systemctl reload "+service
    subprocess.call(cmd,shell=True)


def clear_fpm_user(cpuser):
    fpmdb=dataparse.readjson("/etc/cpnginx/data/fpm.json")
    for fpm in fpmdb:
        fpmconf=fpmdb[fpm][5]+'/'+cpuser+'.conf'
        if os.path.exists(fpmconf):
            os.remove(fpmconf)
            reloadfpm(fpm)
            print ("PHP-FPM disabled  for fpm "+shellcolor.green+fpm+shellcolor.end)


def remove_all_fpm_user():
    fpmdb=dataparse.readjson("/etc/cpnginx/data/fpm.json")
    cmd='/usr/sbin/whmapi1 list_users --outpu=json'
    datas=os.popen(cmd).read()
    result={}
    try:
        result=json.loads(datas)
    except Exception as e:
        print((str(e)))
        pass
    for cpuser in result['data']['users']:
        for fpm in fpmdb:
            fpmconf=fpmdb[fpm][5]+'/'+cpuser+'.conf'
            if os.path.exists(fpmconf):
                os.remove(fpmconf)
                print ("Cpnginx PHP-FPM removed for user.. "+cpuser+".." +shellcolor.green+fpm+shellcolor.end)
    for fpm in fpmdb:
        reloadfpm(fpm)


def find_fpm_sock(fpmconf):
    match='.sock'
    sockpath=None
    with open(fpmconf, 'r') as read_obj:
        for line in read_obj:
            if ((match in line) and (';' not in line)):
                sockpath=line.strip()
    sdata=sockpath.split("=")
    socket=sdata[1].strip()
    return(socket)

def avilable_fpm():
    fpmdb=dataparse.readjson("/etc/cpnginx/data/fpm.json")
    data=[]
    for fpm in fpmdb:
        data.append(str(fpm))
    return(data)














