# -*- coding: ascii -*-

###########################################################################
# clive, video extraction utility
# Copyright (C) 2007-2008 Toni Gundogdu
#
# clive 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 program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 0.1.2-1307 USA
###########################################################################

## The classes that involve locating or constructing file paths

import sys
import os
import subprocess
import errno

__all__ = ['ConfigDir', 'Autodetect']


## The class that wraps absolute paths to config etc. files
class ConfigDir:
    _rcdir = '.clive'
    _rcfile = 'config'
    _cachefile = 'cache'
    _recallfile = 'recall'
    _customfile = 'custom.py'

    ## Constructor
    def __init__(self):
        self._rcdir = os.path.join(os.path.expanduser('~'), self._rcdir)

        try:
            os.makedirs(self._rcdir)
        except OSError, e:
            if e.errno == errno.EEXIST: pass
            else: raise

        self._rcfile = os.path.join(self._rcdir, self._rcfile)
        self._cachefile = os.path.join(self._rcdir, self._cachefile)
        self._recallfile = os.path.join(self._rcdir, self._recallfile)
        self._customfile = os.path.join(self._rcdir, self._customfile)

    ## Return path to ~/.clive directory
    def dir(self):
        return self._rcdir

    ## Return path to rcfile
    def rcfile(self):
        return self._rcfile

    ## Return path to cache file
    def cachefile(self):
        return self._cachefile

    ## Return path to recall file
    def recallfile(self):
        return self._recallfile

    ## Return path to custom file
    def customfile(self):
        return self._customfile


## The class used to locate programs
class Autodetect:
    ## Return path to a program
    def locate(self, cmd, append="", say=None):
        pipe = subprocess.Popen('which %s 2>/dev/null' % cmd,
            shell=1, stdout=subprocess.PIPE).stdout
        data = pipe.read().rstrip('\n')
        path = None
        if len(data) > 0:
            path = '%s %s' % (data, append)
            if say: say('found: %s' % data)
        return path
