#!/usr/bin/env python3
# This program reacts on "Replaying" dbus messages of the dbus2vdr plugin for VDR.
# If a recording on a different filesystem than the VDRDIR's filesystem is played,
# the index file of this recording is opened until replay has been stopped.
# This prevents unwanted umounts by autofs inacitivty timeouts, if the replay
# is paused too long.

import dbus
import dbus2vdr
import os
import configparser
from gi.repository import GLib
from dbus.mainloop.glib import DBusGMainLoop

last_file = None
config_file = "/etc/avahi-linker/default.cfg"
default_vdrdir = '/data/tv'

def on_Replay(*args, **kwargs):
    name, path, status, *_ = args
    global last_file
    if status:
        if not os.lstat(path).st_dev == os.lstat(vdrdir).st_dev:
            last_file = open(os.path.join(path, "index"), 'r')
    else:
        cleanup()

def cleanup(*args, **kwargs):
    global last_file
    try:
        last_file.close()
    except:
        pass
    finally:
        last_file = None

if __name__ == '__main__':
    config = configparser.ConfigParser()
    config.read(config_file)
    vdrdir = config.get('targetdirs', 'vdr', fallback=default_vdrdir)
    vdr_instance_id = config.getint('options', 'vdr_instance_id', fallback=0)
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    DBusGMainLoop(set_as_default=True)
    vdr = dbus2vdr.DBus2VDR(dbus.SystemBus(), instance=vdr_instance_id, watchdog=True)
    vdr.onSignal("Replaying", on_Replay)
    vdr.onSignal("Stop", cleanup)
    GLib.MainLoop().run()
