# +-------------------------------------------------------------------
# | 宝塔Windows面板网站日志切割脚本
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2099 宝塔软件(http://bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author: <cjx@bt.cn>
# +------------------------------------------------------------------
import sys,os,time
import glob,shutil
panelPath = os.getenv('BT_PANEL')
softPath = os.getenv('BT_SETUP')
os.chdir(panelPath)
sys.path.insert(0,panelPath + "/class/")
import public

webserver = public.get_webserver()
if webserver == 'iis':
    print( '★['+time.strftime("%Y/%m/%d %H:%M:%S")+']，IIS不需要切割日志')
    exit();

print( '★['+time.strftime("%Y/%m/%d %H:%M:%S")+'] --> 开始切割日志')
print ('|--当前保留最新的[' + sys.argv[2] + ']份')

logsPath = public.format_path('{}/wwwlogs/'.format(softPath))

px = '.log'
if webserver != 'nginx': px = '-access.log'


def split_logs(oldFileName,num):
    """
    按文件切割日志
    @oldFileName 文件路径
    @num 保留天数
    """
    oldFileName = public.format_path(oldFileName)
    global logsPath
    if not os.path.exists(oldFileName):
        print('|---'+oldFileName+'文件不存在!')
        return

    search_file= oldFileName.replace(px,'')
    logs = sorted(glob.glob(search_file+"_*"))

    count=len(logs)
    num=count - num

    for i in range(count):
        if i>num: break;

        del_file = public.format_path(logs[i])
        os.remove(logs[i])
        print('|---多余日志['+del_file+']已删除!')

    newFileName = oldFileName.replace(px,'') + '_' + time.strftime("%Y-%m-%d_%H%M%S")+ px
    shutil.move(oldFileName,newFileName)
    print('|---已切割日志到:'+public.format_path(newFileName))

def split_all(save):
    """
    切割所有网站日志
    @save 保留天数
    """
    sites = public.M('sites').field('name').select()
    for site in sites:
        oldFileName = logsPath + site['name'] + px
        split_logs(oldFileName,save)

if __name__ == '__main__':
    num = int(sys.argv[2])
    if sys.argv[1].lower().find('all') >= 0:
        split_all(num)
    else:

        siteName = sys.argv[1]
        if siteName[-4:] == '.log':
            siteName = siteName[:-4]
        else:
            siteName = siteName.replace("-access_log",'')

        oldFileName = logsPath + siteName + px

        print('|---切割['+oldFileName+']日志')
        logsPath + siteName + px
        split_logs(oldFileName,num)

    public.serviceReload()