#!/usr/bin/python
# -*- coding: utf8 -*-

# Functionalities common to akabei-db-import and pacman-db-import
#
#   Copyright (C) 2016 Lisa Vitolo <shainer@chakralinux.org>

#   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; either
#   version 2 of the License, or (at your option) any later version.

import sys

def getDatabasePath(pf):
    """Reads the path of the local Pacman database from the configuration.

    Args:
        pf: path of the configuration file.

    Returns:
        The path of the database, or an empty string if none was found.
    """
    try:
        conf = open(pf, "r")
    except IOError, err:
        print str(err)
        print "[!!] This script needs your pacman config file to perform the conversion."
        print "[!!] Use " + sys.argv[0] + " -p <path to your pacman.conf> to specify a different configuration file."
        sys.exit(-1)
    
    for pacmanLine in conf.readlines():
        separatedLine = pacmanLine.partition("=")
        
        optname = separatedLine[0]
        
        # Deletes trailing whitespaces on both sides
        optname = optname.lstrip()
        optname = optname.rstrip()
        
        if (optname == "DBPath"):
            optvalue = separatedLine[2].partition("#")[0] # leaves out comments after the db path
            optvalue = optvalue.lstrip()
            optvalue = optvalue.rstrip()
            
            conf.close()
            return optvalue
    
    conf.close()
    return ""
