#!/usr/bin/env python
# -*- coding: utf-8 -*-

########################################################################################
#                                                                                      #
#   Author: Bertrand Neron,                                                            #
#   Organization:'Biological Software and Databases' Group, Institut Pasteur, Paris.   #  
#   Distributed under GPLv2 Licence. Please refer to the COPYING.LIB document.         #
#                                                                                      #
########################################################################################

import gzip
import time
import stat
import logging
import logging.handlers
 
import os , sys
MOBYLEHOME = None
if os.environ.has_key('MOBYLEHOME'):
    MOBYLEHOME = os.environ['MOBYLEHOME']
if not MOBYLEHOME:
    sys.exit( 'MOBYLEHOME must be defined in your environment' )
if ( os.path.join( MOBYLEHOME , 'Src' ) ) not in sys.path:
    sys.path.append( os.path.join( MOBYLEHOME , 'Src' ) )
        

from Mobyle.ConfigManager import Config
config = Config()
 

log = logging.getLogger('mobrotate' )
log_path = config.log_dir()
defaultFormatter = logging.Formatter(
                '%(name)-10s : %(levelname)-8s : %(filename)-10s: L %(lineno)d : %(asctime)s : %(message)s' ,
                '%a, %d %b %Y %H:%M:%S'
                )
mailHandler = logging.handlers.SMTPHandler( config.mailhost(),
                                            config.sender() ,
                                            config.maintainer()  ,
                                            '[ %s ] Mobyle problem' % config.root_url()
                                            )
mailHandler.setFormatter(defaultFormatter)
log.addHandler(mailHandler)



target_files=['access_log', 'account_log', 'cleaner_log', 'error_log', 'child_log']

try:
    os.chdir(log_path)
except Exception ,err:
    sys.exit(err)

try:
    with open('.month') as month_f:
        rev = month_f.readline()
except IOError, err:
    if err.errno == 2: 
        #the file does not exists
        year =  time.strftime('%Y')
        month = time.strftime('%m')
        month = int(month) - 1
        if month == 0:
            month = 12
            year = int(year) -1
        rev = "{0}{1:02d}".format(year, month)
    else:
        log.critical('cannot rotate logs: {0}'.format(err))
        sys.exit(2)
except Exception, err:
    log.critical('cannot rotate logs: {0}'.format(err))
    sys.exit(2)


for _file in target_files:
    try:
        os.rename(_file, "{0}.{1}".format(_file, rev) ) 
        f = open(_file, 'w')
        f.close()
        os.chmod(_file, stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IROTH) # 644
        log.debug("rotate {0}".format(_file))
    except Exception, err:
        log.critical('cannot rotate {0}: {1}'.format(_file, err))
        continue
        
for _file in target_files:
    file_to_gzip = "{0}.{1}".format(_file, rev)
    if os.path.exists(file_to_gzip):
        try:
            f_in = open(file_to_gzip, 'rb')
            f_out = gzip.open(file_to_gzip + '.gz', 'wb')
            f_out.writelines(f_in)
            os.unlink(file_to_gzip)
        except Exception, err:
            log.error("cannot compress log {0}: {1}".format(file_to_gzip, err))
        finally:
            try:
                f_in.close()
            except:
                pass
            try:
                f_out.close()
            except:
                pass    
with open(".month", 'w') as _f:
    _f.write(time.strftime('%Y%m'))
    
    
