_pg_backup_ctl()
{
    local cur prev opts backupdir word

    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    pos=0

    # Get the backupdir for further information about commands, like our ls.
    for word in ${COMP_WORDS[@]}; do
        let pos=pos+1
        if [ "$word" = "-A" ]; then
            backupdir=${COMP_WORDS[pos]}
            break;
        fi
    done

    # supported tasks
    tasks="setup basebackup lvmbasebackup streambackup rsyncbackup create-lvmsnapshot \
            remove-lvmsnapshot restore currentbackup cleanup ls ls+"

    # options
    opts="-A -D -m -z -l -L -M -n -N -o -h -p -U"

    # provide some basic mount options that are supported by most
    # filesystems
    basic_mount_opts="defaults noatime ro rw remount"

    # check for option specific completions based on the last argument
    case "${prev}" in
        -A|-D|-l|-N)
            # complete directories
            COMPREPLY=( $(compgen -d ${cur}) )
            return 0
            ;;
        -h)
            # complete hostnames
            COMPREPLY=( $(compgen -A hostname ${cur}) )
            return 0
            ;;
        -U)
            # complete usernames
            COMPREPLY=( $(compgen -u ${cur}) )
            return 0
            ;;
        -o)
            # supply a few mount option
            COMPREPLY=( $(compgen -W "${basic_mount_opts}" ${cur}) )
            return 0
            ;;
        restore)
            # return a list of basebackups
            local basebackups

            [ ! -z $backupdir ] || return 0 # exit if no backupdir is present
            basebackups=$( pg_backup_ctl -A $backupdir ls | \
                            grep -E "[0-9]{4}(-[0-9]{2}){2}" | \
                            cut -d" " -f1 )
            COMPREPLY=( $(compgen -W "${basebackups}" ${cur}) )
            return 0
            ;;
        *)
            ;;
    esac

    # check for current completions
    case "${cur}" in
        -*)
            COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
            return 0
            ;;
        *)
            ;;
    esac

    COMPREPLY=( $(compgen -W "${tasks}" -- ${cur}) )
    return 0
}
complete -F _pg_backup_ctl pg_backup_ctl
