# The Akabei 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
}

_akabei()
{
    COMPREPLY=()
    current="${COMP_WORDS[COMP_CWORD]}"
    commands="database changelog deps explicit check owner orphans new group info search local remove clean install repo sync update upgrade newest perform get"
    options="--file --quiet --asdeps --asexplicit --nodeps --force --downloadonly --needed --ignore --ignoregroup --dbonly --nosave --recursive --root --dbpath --cachedir --local"

    # There is only one operation command per command line (and it doesn't have a fixed index in COMP_WORDS due to options)
    # so if one has already been found, don't complete the next similar looking words (they're arguments)
    last=${COMP_CWORD}
    let last=last-1
    operationFound=0
  
    if [[ ${operationFound} == 0 ]] ; then
        for i in `seq 0 ${last}`;
        do
                if [[ ${COMP_WORDS[$i]} != "akabei" && ${COMP_WORDS[$i]} != -* ]] ; then
                    operationFound=1
                fi
        done
    fi
  
    if [[ ${current} != -* && ${operationFound} == 0 ]] ; then # completes an operation command
        COMPREPLY=( $(compgen -W "${commands}" -- ${current}) )
    elif [[ ${current} != -* && ${operationFound} == 1 ]] ; then # completes a package name
        _listPackages
        COMPREPLY=( $(compgen -W "${_packages}" -- ${current}) )
    elif [[ ${current} == --* ]] ; then # completes an option
        COMPREPLY=( $(compgen -W "${options}" -- ${current}) )
    fi
  
    return 0
}

complete -F _akabei akabei
