#compdef gpg gpgv gpg-zip

local curcontext="$curcontext" state line expl ret=1
local -a gpgbasic gpgextra gpgv gpgzip
typeset -A opt_args

gpgv=('(-q --quiet)*'{-v,--verbose}'[increase amount of output]'
  '(-q --quiet -v --verbose)'{-q,--quiet}'[reduce amount of output]'
  '--keyring=[add specified file to list of keyrings]:file:_files'
  '--'{status,logger}'-fd:file descriptor:_file_descriptors'
  '--ignore-time-conflict'
  '--homedir:directory:_directories')

gpgzip=('--gpg[command to use instead of gpg]:command:_command'
  '--gpg-args[gpg arguments]:gpg arguments:'
  '--tar[command to use instead of tar]:command:_command'
  '--tar-args[tar arguments]:tar arguments:'
  '--list-archive[list archive contents]')

gpgbasic=('(-e --encrypt)'{-e,--encrypt}'[encrypt data. this option may be combined  with --sign]'
  {-d,--decrypt}'[decrypt file or stdin]'
  '(-c --symmetric)'{-c,--symmetric}'[encrypt with symmetric cypher only]'
  '(-s --sign)'{-s,--sign}'[make a signature]'
  '*'{-r+,--recipient}'[specify user to encrypt for]:recipient:->public-keys'
  '(-u --local-user)'{-u+,--local-user}'[use name as the user ID to sign]:user attachment:_users'
  '(-o --output)'{-o+,--output}'[write output to file]:output file:_files'
  '(-h --help)'{-h,--help}'[display usage information]'
  '--version[print info on program version and supported algorithms]')

gpgextra=('--decrypt-files[decrypt multiple files]'
  '(-b --detach-sign)'{-b,--detach-sign}'[make a detached signature]'
  '--clearsign[make a clear text signature]'
  '--store[store only]'
  '--verify[verify a signature]'
  '--verify-files[verify a list of files]'
  '(-f --encrypt-files)'{-f,--encrypt-files}'[encrypt files]'
  '--list-keys[list all keys]'
  '--list-public-keys[list all public keys]'
  '--list-secret-keys[list all secret keys]'
  '--list-sigs[lists keys and signatures]:key attachment:->public-keys'
  '--list-options[modify what the various --list-* commands show]'
  '--check-sigs[list key, signatures and check them]:key attachment:->public-keys'
  '--fingerprint[list all keys with their fingerprints]:key attachment:->public-keys'
  '--list-packets[list only the sequence of packets]'
  '--gen-key[generate a new pair key]'
  '--edit-key[a menu for edit yours keys]:key attachment:->public-keys'
  '--sign-key[sign a key]:key attachment:->public-keys'
  '--lsign-key[sign a key but mark as non-exportable]:key attachment:->public-keys'
  '--nrsign-key[sign a key non-revocably]'
  '--delete-key[remove key from public keyring]:key attachment:->public-keys'
  '--delete-secret-key[remove key from public & private keyring]:key attachment:->secret-keys'
  '--delete-secret-and-public-key:key attachment:->secret-keys'
  '--gen-revoke[generate a revocation certificate]'
  '--desig-revoke[generate a designated revocation certificate]'
  '--export[export all key from all keyrings]'
  '--send-keys[send keys to a keyserver]:key attachment:->public-keyids'
  '--export-all[export all key and not OpenPGP compatible keys]'
  '--export-secret-keys:key attachment:->secret-keys'
  '--export-secret-subkeys:key attachment:->secret-keys'
  '--import[import a gpg key from a file]:_files attachment:_files'
  '--fast-import[import a file without build trustdb]:_files attachment:_files'
  '--fetch-keys[fetch key at URIs]:uri:'
  '--recv-keys[receive a list of keys from a keyserver]:key attachment:->public-keyids'
  '--refresh-keys[update all keys from a keyserver]'
  '--search-keys[search for keys on a key server]'
  '--update-trustdb[update the trust database]'
  '--check-trustdb[unattended trust database update]'
  '--fix-trustdb[fix a corrupted trust database]'
  '--export-ownertrust[list the assigned ownertrust values in ASCII format]:file:_files'
  '--import-ownertrust[update the trustdb with a file]:file:_files'
  '--dearmor[de-Armor a file or stdin]'
  '--enarmor[en-Armor a file or stdin]'
  '--print-md[print message digests]:algorithm:->ciphers::file:_files'
  '--print-mds[print message digests]::file:_files'
  '--gen-random:count' '--gen-prime'
  '--warranty[print warranty info]'
  '(-a --armor)'{-a,--armor}'[create ASCII armored output]'
  '--default-key[specify default user-id for signatures]:key:->secret-keys'
  '--default-recipient[specify default recipient]:recipient:->public-keys'
  '--default-recipient-self[use default key as default recipient]'
  '--no-default-recipient[reset default recipient]'
  '*--encrypt-to[specify recipient]:key:->public-keys'
  '(--encrypt-to)--no-encrypt-to[disable the use of all --encrypt-to keys]'
  '(-z --compress)'{-z,--compress}'[specify compression level]:compression level:((0\:no\ compression 1\:minimum 2 3 4 5 6\:default 7 8 9\:maximum))'
  '(-t --textmode)'{-t,--textmode}'[use canonical text mode]'
  '(-n --dry-run)'{-n,--dry-run}"[don't make any changes]"
  '(-i --interactive --batch)'{-i,--interactive}'[prompt before overwriting files]'
  '(-i --interactive --no-batch)--batch[use batch mode]'
  '--no-tty[never output to tty]'
  '(--batch)--no-batch[disable batch mode]'
  '(--no)--yes[assume "yes" on most questions]'
  '(--yes)--no[assume "no" on most questions]'
  '--default-cert-check-level:check level:((0\:no\ claim 1\:no\ verification 2\:casual\ verification 3\:extensive\ verification))'
  '--trusted-key[assume that the specified key is trustworthy]:long key id'
  '--always-trust[skip key validation]'
  '--keyserver[specify key server to use]:key server:_hosts'
  '--keyserver-options[specify keyserver options]:options'
  '--import-options[specify options for importing keys]:options'
  '--export-options[specify options for exporting keys]:options'
  '--show-photos' '--no-show-photos' '--photo-viewer:command:_command_names -e'
  '--exec-path:path:_dir_list'
  '--show-keyring[display keyring name when listing keys]'
  '--secret-keyring[add specified file to list of secret keyrings]:file:_files'
  '--charset:character set:(iso-8859-1 iso-8859-2 koi8-r utf-8)'
  '--utf8-strings' '--no-utf8-strings[arguments are not in UTF8]'
  '(--no-options)--options[specify file to read options from]:options file:_files'
  "(--options)--no-options[don't read options file]"
  '--'{attribute,passphrase,command}'-fd:file descriptor:_file_descriptors'
  '--sk-comments[include secret key comments when exporting keys]'
  '(--emit-version)--no-emit-version[omit version string in clear text signatures]'
  '(--no-emit-version)--emit-version[force writing of version string in clear text signatures]'
  '(-N --notation-data)'{-N,--notation-data}'[put parameter in signature]:name=value'
  '(--no-show-notation)--show-notation[show key signature notations]'
  "(--show-notation)--no-show-notation[don't show key signature notations]"
  '--set-policy-url:policy URL'
  '(--no-show-policy-url)--show-policy-url'
  '(--show-policy-url)--no-show-policy-url'
  '--set-filename[specify file which is stored in messages]:file:_files'
  '(--for-your-eyes-only)--for-your-eyes-only'
  '(--for-your-eyes-only)--no-for-your-eyes-only'
  '--completes-needed:number' '--marginals-needed:number' '--max-cert-depth:number'
  '--'{{,disable-,s2k-}cipher,{,s2k-,cert-}digest,disable-pubkey}'-algo:cipher:->ciphers'
  '--s2k-mode:value' '--simple-sk-checksum'
  '--compress-algo:compression algorithm:((0\:disable\ compression 1\:zlib 2\:rfc1950))'
  '--no-sig-cache' '--no-sig-create-check' '--'{,no-}'auto-check-trustdb' '--throw-keyid'
  '--not-dash-escaped' '--'{,no-}'escape-from-lines' '--'{,no-}'use-agent'
  '--rfc1991' '--'{,no-}'pgp2' '--'{,no}'pgp6' '--'{,no}'pgp7' '--openpgp'
  '--'{,no-}'force-v3-sigs' '--'{,no}'force-v4-certs' '--force-mdc' '--disable-mdc'
  '--'{,no-}'allow-non-selfsigned-uid' '--allow-freeform-uid'
  '--ignore-valid-from'
  '--ignore-crc-error' '--ignore-mdc-error' '--lock-once' '--lock-multiple' '--lock-never'
  '--no-random-seed-file' '--no-verbose' '--no-greeting' '--no-secmem-warning'
  '--no-permission-warning' '--no-mdc-warning' '--no-armor' '--no-default-keyring'
  '--skip-verify' '--with-colons' '--with-key-data' '--with-fingerprint'
  '--fast-list-mode' '--fixed-list-mode' '--list-only' '--no-literal' '--set-filesize'
  '--emulate-md-encode-bug' '--show-session-key' '--override-session-key:string'
  '--'{,no-}'ask-sig-expire' '--'{,no}'ask-cert-expire' '--'{,no}'expert'
  '--merge-only' '--allow-secret-key-import' '--try-all-secrets'
  '--enable-special-filenames' '--no-expensive-trust-checks' '--group:name=value'
  '--preserve-permissions' '--personal-'{cipher,digest,compress}'-preferences:string'
  '--card-edit[present smartcard menu]' '--card-status[show smartcard content]'
  '--change-pin[present menu to change smartcard pin]'
  '--list-config[display internal configuration parameters]'
  '--hidden-recipient[hidden recipient]:recipient:->public-keys'
  '--dump-options[show all options]' '--default-preference-list:string'
  '--fetch-keys:URIs:' '--gpgconf-list' '--gpgconf-test'
  '--hidden-encrypt-to:recipient:->public-keys'
  '--compress-level:integer:'
  '--bzip2-compress-level:integer:' '--bzip2-decompress-lowmem'
  '--default-sig-expire' '--default-cert-expire' '--no-ask-cert-expire'
  '--default-cert-level:integer:'
  '--min-cert-level' '--ask-cert-level' '--no-ask-cert-level'
  '--max-output[maximum output generated when processing file]:bytes:'
  '--gpg-agent-info[override GPG_AGENT_INFO]:'
  '--primary-keyring:file:_files'
  '--'{,no-}'verify-options:parameters:_multi_parts -q -S, ","
    "(show-photos show-policy-urls show-notations show-std-notations
    show-user-notations show-keyserver-urls show-uid-validity show-unusable-uids
    show-primary-uid-only pka-lookups pka-trust-increase)"'
  '--debug:flags:' '--debug-all' '--status-file:file:'
  '--attribute-file:file:' '--load-extension:file:_files'
  '--gnupg' '--rfc2440' '--rfc4880' '--pgp8'
  '--s2k-count:integer:' '--'{,no-}'throw-keyids'
  '--sig-notation:name=value:' '--cert-notation:name=value:'
  '--passphrase-file:file:_files' '--passphrase-repeat:integer:'
  '--command-file:file:_files' '--trustdb-name:file:_files'
  '--'{,no-}'require-secmem'
  '--trust-model:trust model:((pgp classic direct always auto))'
  '--sig-policy-url:string:' '--cert-policy-url:string:'
  '--sig-keyserver-url:string:' '--comment[comment]:comment:'
  '--no-comments[disable comments]'
  '--logger-file[write log to file]:file:_files'
  '--'{,no-}'use-embedded-filename'
  '--rebuild-keydb-caches[create signature caches in keyring]'
  '--default-keyserver-url:name:'
  '--display-charset[set native charset]:charset:((iso-8859-1 iso-8859-2 iso-8859-15 koi8-r utf-8))'
  '--ungroup[remove group]:group name:'
  '--no-groups[remove all entries from --group list]'
  '--'{,no}'mangle-dos-filenames'
  '--enable-progress-filter[enable progress status output]'
  '--multifile[process multiple files]'
  '--keyid-format[key id format]:key format:((short 0xshort long 0xlong))'
  '--exit-on-status-write-error[exit immediately on error write]'
  '--limit-card-insert-tries:integer:'
  '--reader-port[card reader port]:port:'
  '--ctapi-driver[file to use to access smartcard reader]:file:_files'
  '--pcsc-driver[file to use to access smartcard reader]:file:_files'
  '--disable-ccid' '--debug-ccid-driver'
  '--'{enable,disable}'-dsa2'
  '--'{,no-}'allow-multiple-messages' '--'{,no-}'require-cross-certification'
  '--auto-key-locate:parameters:' '--no-auto-key-locate'
  '--dump-options[show all options]')

case "$service" in
  gpg)
    _arguments -C -s -S -A "-*" $gpgbasic $gpgextra $gpgv '*:args:->args' && ret=0
    ;;

  gpgv)
    _arguments -C -s -S -A "-*" $gpgv '*:args:->args' && ret=0
    ;;

  gpg-zip)
    _arguments -C -s -S -A "-*" $gpgbasic $gpgzip '*:args:->args' && ret=0
    ;;
esac

if [[ $state = args ]]; then
  if (( ${+opt_args[--export]} || ${+opt_args[--list-keys]} || ${+opt_args[--list-public-keys]} )); then
    state=public-keys
  elif (( ${+opt_args[--list-secret-keys]} )); then
    state=secret-keys
  else
    _files && return
  fi
fi

# We need to keep some arguments to get a consistent list of keys
# etc.
local -a needed
integer krind=${words[(I)--keyring(|=*)]}
needed=(${words[(r)--no-default-keyring]})
if (( krind )); then
  # We have a --keyring option.  We can't be completing its
  # argument because that was handled above, so it must be complete.
  if [[ $words[krind] = --keyring ]]; then
    if [[ -n $words[krind+1] ]]; then
      needed+=(--keyring=$words[krind+1])
    fi
  else
    needed+=($words[krind])
  fi
fi

case "$state" in
  public-keys)
    _wanted public-keys expl 'public key' \
	compadd ${${(Mo)$(_call_program public-keys gpg $needed --list-public-keys --list-options no-show-photos 2>/dev/null):%<*>}//(<|>)/} && return
  ;;
  secret-keys)
    _wanted secret-keys expl 'secret key' compadd \
	${${(Mo)$(_call_program secret-keys gpg $needed --list-secret-keys --list-options no-show-photos 2>/dev/null):%<*>}//(<|>)/} && return
  ;;
  ciphers)
    _wanted ciphers expl cipher compadd \
        ${${(s.,.)${(M)${(f)"$(_call_program ciphers gpg $needed --version)"}:#Cipher*}#*:}# } && return
  ;;
  (public-keyids)
    _wanted public-keys expl 'public keyid' \
	compadd ${${${(M)${(f)"$(_call_program public-keyids gpg $needed --list-public-keys --list-options no-show-photos 2>/dev/null)"}:%pub*}#pub */}%% *} && return
  ;;
esac

return ret
