# The PAkabei bash completion script
#
#   Copyright (C) 2012 Lisa Vitolo <shainer@chakra-project.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.

_packages=""
_databasedir=""

# Function: _readDbPath
# Reads the database path from Akabei configuration file
_readDbPath()
{
    while read line
    do
        if [[ ${line} == DatabaseDir* ]] ; then
            _databasedir=$( echo ${line} | cut -d = -f2 )
            _databasedir=$( echo ${_databasedir} | sed 's/^[ \t]*//;s/[ \t]*$//' )
            break
        fi
    done < "/etc/akabei.conf"
}

# Function: _listPackages
# Reads all the package names from the available databases
_listPackages()
{
    _readDbPath

    if [[ -z "${_databasedir}" ]] ; then
        return 0
    fi

    for filename in `ls ${_databasedir}` ; do
        if [[ ${filename} == *.db ]] ; then
            _packages+=$( sqlite3 -list "${_databasedir}/${filename}" 'select name from packages'; )
        fi
    done

    true
}

_pakabei()
{
    COMPREPLY=()
    current="${COMP_WORDS[COMP_CWORD]}"
    options="--file --quiet --asdeps --asexplicit --nodeps --force --downloadonly --needed --ignore --ignoregroup --dbonly --nosave --recursive --root --dbpath --cachedir --local"

    if [[ ${current} == --* ]] ; then # completes an option
        COMPREPLY=( $(compgen -W "${options}" -- ${current}) )
    elif [[ ${current} != -* ]] ; then # completes a package name
        _listPackages
        COMPREPLY=( $(compgen -W "${_packages}" -- ${current}) )
    fi
  
    return 0
}

complete -F _pakabei pakabei
