## Bu dosya ansible tarafindan yonetilmektedir!
## Burada yapilan degisikliklerin uzerine yazilir!!
{{ ansible_managed }}

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

import socket
import os
import time
from datetime import datetime, timedelta
import subprocess
import sys

__author__ = "ULAKBIM Pardus Ahtapot"
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "ULAKBIM Pardus Ahtapot"
__email__ = "bilgi@pardus.org.tr"
__status__ = "Production"

args = sys.argv

if len(args)!=2:
    print "Use as ahtapot-pyBekci.py path_to_copy_archive_file"
    exit()
else:

    copy_path = args[1]

    hostname = socket.gethostname()
    host_path = "/var/log/sudo-io/" + str(hostname) + "/"
    user_list = [user for user in os.listdir(host_path) if os.path.isdir(host_path+user)]

    # to prepare all user lists /var/log/sudo-io/[HOST]/[USER]/00
    user_paths = []
    for i in range(0, len(user_list)):
        user_paths.append(host_path+user_list[i]+"/00/")

    # to prepare all user session lists [{"[USER]":["5C","5A"]}]
    users_sessions = []
    for user_path in user_paths:
        userdict = {}
        sessions = [session for session in os.listdir(user_path) if os.path.isdir(user_path+session)]
        userdict[user_path] = sessions
        users_sessions.append(userdict)

    # to prepare path of session folders with user
    folders_to_tar = []
    current_date = datetime.now()
    for user_session in users_sessions:
        for key, value in user_session.items():
            user_dict = {}
            user = key.split("/")[-4]
            user_dict[user] = []
            for v in value:
                folder_path = key + v + "/"
                #get session folder's full path and compare ctime with 3 days ago
                folder_time = datetime.strptime(time.ctime(os.path.getctime(folder_path)),"%a %b %d %H:%M:%S %Y")
                if folder_time < (current_date - timedelta(days=3)):
                    user_dict[user].append(folder_path)
            #add old sessions path to list to archive
            folders_to_tar.append(user_dict)

    # move all sessions to specified user folder and archive it.
    str_date = current_date.strftime("%Y_%m_%d-%H:%M:%S")
    for user_folders in folders_to_tar:
        for key, value in user_folders.items():
            #key = UserName
            if len(value)>0:
                subprocess.call(["mkdir " + copy_path + key], shell=True)
                for folder in value:
                    #folder = complete session folder path
                    subprocess.call(["mv "+folder+" " + copy_path + key], shell=True)
                #archive session folders as "UserName_CurrentDate.tar.gz"
                subprocess.call(["cd " + copy_path + key + "&& tar zcf " + copy_path + key + "_" + str_date + ".tar.gz" + " *"], shell=True)
                subprocess.call(["rm -rf " + copy_path + key], shell=True)
            else:
                print "No Session to Archive"
