#!/usr/bin/python
# (c) 2006 - Oliver Grawert (Canonical Ltd.)
# (c) 2006 - Scott Balneaves
# 
# delayed_mounter - a delayed mount monitoring script for ltsp local devices 
#
# This software is distributed under the terms and conditions of the
# GNU General Public License. See file GPL for the full text of the license.
#

import sys
import os
import time
from subprocess import *

def main():
    while True:
        if os.path.exists('/tmp/.ltspfs-socket') and \
           os.path.exists('/var/run/.delayed-mount'):
            f = open('/var/run/.delayed-mount')
            mounts = f.readlines()
            f.close()

            for mount in mounts:
                if not os.path.exists(mount.split()[0]):
                    os.mkdir(mount.split()[0])
                fd = open('/etc/fstab', 'r')
                fstablines = fd.readlines()
                fd.close()
                match=False
                for i in range(len(fstablines)):
                    if fstablines[i].find(mount.split()[1]) >= 0:
                        match=True
                if not match:
                    fstablines.append("/dev/" + mount.split()[1] + " " + mount.split()[0] + " auto defaults 0 0\n")
                    fd = open("/etc/fstab", 'w')
                    fd.writelines(fstablines)
                    fd.close()

                mount_command = ['/usr/bin/ssh', '-S', '/tmp/.ltspfs-socket',
                                 'server', '/usr/sbin/ltspfsmounter',
                                 mount.split()[0], 'add']
                env = os.environ.copy()
                try:
                    call(mount_command, env=env)
                except OSError, e:
                    print >>sys.stderr, "mount failed:", e
            os.unlink('/var/run/.delayed-mount')
        else:
            time.sleep(5)

if __name__ == "__main__":
    # do the UNIX double-fork magic, see Stevens' "Advanced 
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    try:
        pid = os.fork()
        if pid > 0:
            # exit first parent
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    # decouple from parent environment
    os.chdir("/")
    os.setsid()
    os.umask(0)

    # do second fork
    try:
        pid = os.fork()
        if pid > 0:
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    # start the daemon main loop
    main()
