# Copyright (C) 2009 LottaNZB Development Team
# 
# This program 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; version 3.
# 
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

"""
This module is based on the BaseDirectory module provided by pyxdg:

    http://www.freedesktop.org/wiki/Software/pyxdg

The freedesktop.org Base Directory specification provides a way for
applications to locate shared data and configuration:

    http://standards.freedesktop.org/basedir-spec/

This module is also capable of reading the user-dirs.dirs file.
"""

import re
import logging
log = logging.getLogger(__name__)

from os import environ
from os.path import join, exists, expandvars, expanduser

__all__ = ["CONFIG_HOME", "CACHE_HOME", "DATA_HOME", "DATA_DIRS",
    "CONFIG_DIRS", "USER_DIRS"]

CONFIG_HOME = environ.get("XDG_CONFIG_HOME", expanduser("~/.config"))
CACHE_HOME = environ.get("XDG_CACHE_HOME", expanduser("~/.cache"))
DATA_HOME = environ.get("XDG_DATA_HOME", expanduser("~/.local/share"))

DATA_DIRS = [DATA_HOME] + \
    environ.get("XDG_DATA_DIRS", "/usr/local/share:/usr/share").split(":")

CONFIG_DIRS = [CONFIG_HOME] + \
    environ.get("XDG_CONFIG_DIRS", "/etc/xdg").split(":")

# Remove empty entries.
DATA_DIRS = [data_dir for data_dir in DATA_DIRS if data_dir]
CONFIG_DIRS = [config_dir for config_dir in CONFIG_DIRS if config_dir]

"""
The user-dirs.dirs file in CONFIG_HOME can be used to specify the location of
common user directories used for downloads, pictures, music, etc. The following
keys can be defined in this particular file (and overridden using environment
variables):

XDG_DESKTOP_DIR
XDG_DOWNLOAD_DIR
XDG_TEMPLATES_DIR
XDG_PUBLICSHARE_DIR
XDG_DOCUMENTS_DIR
XDG_MUSIC_DIR
XDG_PICTURES_DIR
XDG_VIDEOS_DIR

Refer to http://www.freedesktop.org/wiki/Software/xdg-user-dirs for more
information.
"""
USER_DIRS = {}

try:
    user_dirs_file = open(join(CONFIG_HOME, "user-dirs.dirs"))
    pattern = re.compile("^(?P<key>[A-Z_]+)=\s*\"(?P<value>.+)\"\s*$")
    
    for line in user_dirs_file.readlines():
        match = pattern.match(line)
        
        if match:
            USER_DIRS[match.group("key")] = expandvars(match.group("value"))
    
    for key in USER_DIRS:
        USER_DIRS[key] = environ.get(key, USER_DIRS[key])
except IOError:
    log.debug("Could not load the user-dirs.dirs file.")
