#!/bin/bash

_meric()
{
  local cur=`_get_cword`
  local prev="${COMP_WORDS[COMP_CWORD-1]}"
  local first="${COMP_WORDS[1]}"

  local actions="-S -Syu -Su -Ss -Ssq -Si -Sc -Scc -G -h --help"

  local options="--quiet --ignore --noconfirm --asexplicit --asdeps --noedit --auronly --devel --skipinteg --cleandeps --skip-repo --sign --keeptar"

  local pacmanconf='/etc/pacman.conf'
  local dbpath="$(cat $pacmanconf | sed -n '/^\s*DBPath\s*=\s*\([a-zA-Z0-9\s/\\]\+\)/{s//\1/;p;};')"
  [[ "$dbpath" == "" ]] && dbpath='/var/lib/pacman'

  if [ $COMP_CWORD == 1 ]; then
    if [[ "$cur" == -* ]]; then
      COMPREPLY=($(compgen -W "$actions" -- "$cur"))
    elif [[ "$cur" != "" ]]; then
      local locpac="$(ls -1 /var/lib/pacman/local | sed -n '/^\(.*\)\(-[^-]\+\)\{2\}$/{s//\1/;p;};')"
      unset syncpac
      for arc in $(ls -1 "$dbpath/sync"); do
        local syncpac+=" $(bsdtar -tf "$dbpath/sync/$arc" | sed -n '/^\(.*\)\(-[^-]\+\)\{2\}\/$/{s//\1/;p;};')"
        echo "$syncpac"
      done
      COMPREPLY=($(compgen -W "$syncpac $locpac" -- "$cur"))
    fi
  else
    if [[ "$cur" == -* ]]; then
      COMPREPLY=($(compgen -W "$options" -- "$cur"))
    else
      case "$first" in
        -G|-Su|-Syu|-Sc|-Scc|-h|--help)
          COMPREPLY=()
          return
          ;;
        -*)
          local locpac="$(ls -1 /var/lib/pacman/local | sed -n '/^\(.*\)\(-[^-]\+\)\{2\}$/{s//\1/;p;};')"
          unset syncpac
          for arc in $(ls -1 "$dbpath/sync"); do
            local syncpac+=" $(bsdtar -tf "$dbpath/sync/$arc" | sed -n '/^\(.*\)\(-[^-]\+\)\{2\}\/$/{s//\1/;p;};')"
          done
          COMPREPLY=($(compgen -W "$syncpac $locpac" -- "$cur"))
          ;;
      esac
    fi
  fi
}

complete -F _meric meric

# vim:ts=2 sw=2 et
