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

import sys
import os
import datetime

path = os.path.abspath(os.path.dirname(__file__))
path = '/'.join(path.split('/')[0:-1])
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'wifiadmin.settings'

from main.models import MyUser, Log, MySession
from django.conf import settings

Log.objects.create(msg='Выбираем активные сессии', type='debug') 
sessions = MySession.objects.filter(online=True)
for session in sessions:
    Log.objects.create(msg='В активных сессиях ищем просроченные', type='debug') 
    if session.start + datetime.timedelta(seconds=settings.SESSION_TIME) <= datetime.datetime.now():
        Log.objects.create(msg='Отключаем пользователя ' + session.user.userName.encode('utf8'), type='debug') 
        os.system("{0} {1} {2} {3}".format(settings.SUDO_PATH, settings.FW_SCRIPT, 'delete', session.ip))
        session.online = False
        session.end = datetime.datetime.now()
        session.save()
        Log.objects.create(msg='Сессия для пользователя ' + session.user.userName.encode('utf8') + ' закрыта', type='cron')
