#!/usr/bin/python3
## -*- coding: utf-8 -*-
#
# «mythvideo-monitor» - Utility to monitor video storage groups and 
#                         automatically add to mythtv database, scan for
#                         metadata and set group permissions to mythtv with rw 
#
# Copyright (C) 2011, Thomas Mashos, for Mythbuntu
#
# Mythbuntu-bare is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this application; if not, write to the Free Software Foundation, Inc., 51
# Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
##################################################################################

import pyinotify
import logging
import shutil
import os
import tarfile
import datetime

logger = logging.getLogger('mythbuntu-bare')
hdlr = logging.FileHandler('/var/log/mythbuntu-bare-server.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.WARNING)

INDIR="/var/lib/mythtv/bare/"
ACTOR="<Processor> "

wm = pyinotify.WatchManager()
mask = pyinotify.IN_CLOSE_WRITE
wm.add_watch(INDIR+"files/", mask, rec=True)

class PTmp(pyinotify.ProcessEvent):
  def process_IN_CLOSE_WRITE(self, event):
    self.process_file(event.name)
    logger.info(ACTOR+"Received file: %s " % event.name)

  def process_file(self, FILENAME):
    logger.info(ACTOR+"Processing file: %s " % FILENAME)
    FULLPATH=INDIR+"files/"+FILENAME
    if FILENAME.endswith(".tar.gz"):
      if tarfile.is_tarfile(FULLPATH):
        shutil.move(FULLPATH, INDIR+"backup/")
      else:
        logger.error(ACTOR+"%s is not a valid tarfile" % FILENAME)
    elif FILENAME.endswith(".barelog"):
      f = open(FULLPATH)
      LINE = f.readline()
      HOST, LASTBACKUP, LASTSEEN, STATUS = LINE.strip("\n").split("\t")
      f.close()
      dbtmp = open(INDIR+"client.dbtmp", "w")
      db = open(INDIR+"client.db", "r")
      LINES=db.readlines()
      for l in LINES:
        DHOST, DLASTBACKUP, DLASTSEEN, DSTATUS = l.strip("\n").split("\t")
        if not DHOST == HOST:
          dbtmp.write(DHOST+"\t"+DLASTBACKUP+"\t"+DLASTSEEN+"\t"+DSTATUS+"\n")
      dbtmp.write(HOST+"\t"+LASTBACKUP+"\t"+str(datetime.datetime.now())+"\t"+STATUS+"\n")
      db.close()
      dbtmp.close()
      os.remove(INDIR+"client.db")
      shutil.move(INDIR+"client.dbtmp", INDIR+"client.db")      
      os.remove(FULLPATH)
    else:
      logger.error(ACTOR+"Unknown file: %s " % FILENAME)

notifier = pyinotify.Notifier(wm, PTmp())

while True:
  try:
    notifier.process_events()
    if notifier.check_events():
     notifier.read_events()
  except KeyboardInterrupt:
    notifier.stop()
    break

