#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2009, Jonas Jonsson <jonas@websystem.se>
# All rights reserved.
#
# See file LICENSE for license details
#

import sys
import os
import subprocess
from RarDirFs import rardirfs
from optparse import OptParseError, OptionParser
import fuse

def unrar_available():
    '''
        Check if unrar is available by calling it.
    '''

    try:
        subprocess.call('unrar', stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        return True
    except OSError:
        return False

def main():
    usage = "%prog srcdir mountpoint [options]"
    desc ="""Mount a directory read-only with all rar archives "unpacked". Only uncompressed archives are supported."""
    rarDirFs = rardirfs.RarDirFs(version="%prog 0.1", usage=usage,
            description=desc, dash_s_do='setsingle')
    rarDirFs.parser.add_option(mountopt="only_first", metavar="OPT",
            default="auto", type="choice", choices=['yes', 'no', 'auto'],
            help="show only first file in archive: yes, no, auto [default: %default]")
    rarDirFs.parser.add_option(mountopt="filter", metavar="FILE",
            default="/etc/rardirfs/filter",
            help="hide files matching pattern in FILE [default: %default]")
    rarDirFs.parser.add_option(mountopt="flatten", metavar="FILE",
            default="/etc/rardirfs/flatten",
            help="flatten directories matching pattern in FILE [default: %default]")
    rarDirFs.parser.add_option(mountopt="cache_path", metavar="PATH",
            default="/var/cache/rardirfs",
            help="store files from compressed archives in PATH. [default: %default]")

    rarDirFs.parser.add_option(mountopt="disable_unrar", dest="enable_unrar", action="store_false",
            help="disable support for compressed archives")

    rarDirFs.parse(values=rarDirFs, errex=1)
    (options, args) = rarDirFs.cmdline

    # Add default options
    if not options.filter and os.path.isfile("/etc/rardirfs/filter"):
        options.filter = "/etc/rardirfs/filter"
    if not options.flatten and os.path.isfile("/etc/rardirfs/flatten"):
        options.flatten = "/etc/rardirfs/flatten"
    if not options.only_first:
        options.only_first = 'auto'
    if not options.cache_path:
        options.cache_path = '/var/cache/rardirfs'
    if options.enable_unrar == None:
        options.enable_unrar = unrar_available()

    options.cache_path = os.path.abspath(options.cache_path)

    if rarDirFs.fuse_args.mount_expected():
        if len(args) != 1:
            OptionParser.error(rarDirFs.parser, "missing srcdir")
        elif not os.path.isdir(args[0]):
            OptionParser.error(rarDirFs.parser,
                "bad srcdir {0}, not a directory.".format(args[0]))
        else:
            rarDirFs.srcdir = os.path.abspath(args[0])

        if not options.only_first in ('yes', 'no', 'auto'):
            OptionParser.error(rarDirFs.parser, 'only yes, no and auto is valid arguments to only_first')
    try:
        rarDirFs.main()
    except fuse.FuseError, e:
        print e
        sys.exit(1)

if __name__ == '__main__':
    main()
