#!/bin/bash

# (The MIT License)
#
# Copyright (c) 2014 Andrey Smirnov
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the 'Software'), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

__aptly_mirror_list()
{
  aptly mirror list -raw
}

__aptly_repo_list()
{
  aptly repo list -raw
}

__aptly_snapshot_list()
{
  aptly snapshot list -raw
}

__aptly_published_distributions()
{
  aptly publish list -raw | cut -d ' ' -f 2 | sort | uniq
}

__aptly_published_prefixes()
{
  aptly publish list -raw | cut -d ' ' -f 1 | sort | uniq
}

__aptly_prefixes_for_distribution()
{
  aptly publish list -raw | awk -v dist="$1" '{ if (dist == $2) print $1 }' | sort | uniq
}

_aptly()
{
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    commands="api config db graph mirror package publish repo serve snapshot task version"
    options="-architectures= -config= -db-open-attempts= -dep-follow-all-variants -dep-follow-recommends -dep-follow-source -dep-follow-suggests -dep-verbose-resolve -gpg-provider="
    db_subcommands="cleanup recover"
    mirror_subcommands="create drop edit show list rename search update"
    publish_subcommands="drop list repo snapshot switch update"
    snapshot_subcommands="create diff drop filter list merge pull rename search show verify"
    repo_subcommands="add copy create drop edit import include list move remove rename search show"
    package_subcommands="search show"
    task_subcommands="run"
    config_subcommands="show"
    api_subcommands="serve"

    local cmd subcmd numargs numoptions i

    numargs=0
    numoptions=0

    for (( i=1; i < $COMP_CWORD; i++ )); do
      if [[ -n "$cmd" ]]; then
        if [[ ! -n "$subcmd" ]]; then
          subcmd=${COMP_WORDS[i]}
          numargs=$(( COMP_CWORD - i - 1 ))
        else
          if [[ "${COMP_WORDS[i]}" == -* ]]; then
            numoptions=$(( numoptions + 1 ))
            numargs=$(( numargs - 1 ))
          fi
        fi
      else
        if [[ ! "${COMP_WORDS[i]}" == -* ]]; then
          cmd=${COMP_WORDS[i]}
        fi
      fi
    done

    if [[ ! -n "$cmd" ]];
    then
      case "$cur" in
            -*)
              COMPREPLY=($(compgen -W "${options}" -- ${cur}))
              return 0
            ;;
            *)
              COMPREPLY=($(compgen -W "${commands}" -- ${cur}))
              return 0
            ;;
        esac
    fi

    if [[ ! -n "$subcmd" ]];
    then
        case "$prev" in
            "db")
              COMPREPLY=($(compgen -W "${db_subcommands}" -- ${cur}))
              return 0
            ;;
            "mirror")
              COMPREPLY=($(compgen -W "${mirror_subcommands}" -- ${cur}))
              return 0
            ;;
            "repo")
              COMPREPLY=($(compgen -W "${repo_subcommands}" -- ${cur}))
              return 0
            ;;
            "snapshot")
              COMPREPLY=($(compgen -W "${snapshot_subcommands}" -- ${cur}))
              return 0
            ;;
            "publish")
              COMPREPLY=($(compgen -W "${publish_subcommands}" -- ${cur}))
              return 0
            ;;
            "package")
              COMPREPLY=($(compgen -W "${package_subcommands}" -- ${cur}))
              return 0
            ;;
            "task")
              COMPREPLY=($(compgen -W "${task_subcommands}" -- ${cur}))
              return 0
            ;;
            "config")
              COMPREPLY=($(compgen -W "${config_subcommands}" -- ${cur}))
              return 0
            ;;
            "api")
              COMPREPLY=($(compgen -W "${api_subcommands}" -- ${cur}))
              return 0
            ;;
            *)
            ;;
        esac
    fi

    case "$cmd" in
      "mirror")
        case "$subcmd" in
          "create")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-filter= -filter-with-deps -force-components -ignore-signatures -keyring= -with-installer -with-sources -with-udebs" -- ${cur}))
                return 0
              fi
            fi
          ;;
          "edit")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-archive-url= -filter= -filter-with-deps -ignore-signatures -keyring= -with-installer -with-sources -with-udebs" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_mirror_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "show")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-with-packages" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_mirror_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "search")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-format= -with-deps" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_mirror_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "rename")
            if [[ $numargs -eq 0 ]]; then
              COMPREPLY=($(compgen -W "$(__aptly_mirror_list)" -- ${cur}))
              return 0
            fi
          ;;
          "drop")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-force" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_mirror_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "list")
            if [[ $numargs -eq 0 ]]; then
                COMPREPLY=($(compgen -W "-raw" -- ${cur}))
              return 0
            fi
          ;;
          "update")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-force -download-limit= -ignore-checksums -ignore-signatures -keyring= -skip-existing-packages" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_mirror_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
        esac
      ;;
      "repo")
        case "$subcmd" in
          "add")
            case $numargs in
              0)
                if [[ "$cur" == -* ]]; then
                  COMPREPLY=($(compgen -W "-force-replace -remove-files" -- ${cur}))
                else
                  COMPREPLY=($(compgen -W "$(__aptly_repo_list)" -- ${cur}))
                fi
                return 0
              ;;
              1)
                _filedir '@(deb|dsc|udeb)'
                return 0
              ;;
            esac
          ;;
          "copy"|"move")
            case $numargs in
              0)
                if [[ "$cur" == -* ]]; then
                  COMPREPLY=($(compgen -W "-with-deps -dry-run" -- ${cur}))
                else
                  COMPREPLY=($(compgen -W "$(__aptly_repo_list)" -- ${cur}))
                fi
                return 0
              ;;
              1)
                COMPREPLY=($(compgen -W "$(__aptly_repo_list)" -- ${cur}))
                return 0
              ;;
            esac
          ;;
          "create")
            case $numargs in
              0)
                if [[ "$cur" == -* ]]; then
                  COMPREPLY=($(compgen -W "-comment= -distribution= -component= -uploaders-file=" -- ${cur}))
                  return 0
                fi
                return 0
              ;;
              1)
                COMPREPLY=($(compgen -W "from" -- ${cur}))
                return 0
              ;;
              2)
                COMPREPLY=($(compgen -W "snapshot" -- ${cur}))
                return 0
              ;;
              3)
                COMPREPLY=($(compgen -W "$(__aptly_snapshot_list)" -- ${cur}))
                return 0
              ;;
            esac
          ;;
          "drop")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-force" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_repo_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "edit")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-comment= -distribution= -component= -uploaders-file=" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_repo_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "search")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-format= -with-deps" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_repo_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "list")
            if [[ $numargs -eq 0 ]]; then
                COMPREPLY=($(compgen -W "-raw" -- ${cur}))
              return 0
            fi
          ;;
          "include")
            case $numargs in
              0)
                if [[ "$cur" == -* ]]; then
                  COMPREPLY=($(compgen -W "-accept-unsigned -force-replace -ignore-signatures -keyring= -no-remove-files -repo= -uploaders-file=" -- ${cur}))
                else
                  comptopt -o filenames 2>/dev/null
                  COMPREPLY=($(compgen -f -- ${cur}))
                  return 0
                fi
                return 0
              ;;
            esac
          ;;
          "import")
            case $numargs in
              0)
                if [[ "$cur" == -* ]]; then
                  COMPREPLY=($(compgen -W "-with-deps -dry-run" -- ${cur}))
                else
                  COMPREPLY=($(compgen -W "$(__aptly_mirror_list)" -- ${cur}))
                fi
                return 0
              ;;
              1)
                COMPREPLY=($(compgen -W "$(__aptly_repo_list)" -- ${cur}))
                return 0
              ;;
            esac
          ;;
          "remove")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-dry-run" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_repo_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "show")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-with-packages" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_repo_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "rename")
            if [[ $numargs -eq 0 ]]; then
              COMPREPLY=($(compgen -W "$(__aptly_repo_list)" -- ${cur}))
              return 0
            fi
          ;;
        esac
      ;;
      "snapshot")
        case "$subcmd" in
          "create")
            case $numargs in
              1)
                COMPREPLY=($(compgen -W "from empty" -- ${cur}))
                return 0
              ;;
              2)
                if [[ "$prev" == "from" ]]; then
                  COMPREPLY=($(compgen -W "mirror repo" -- ${cur}))
                  return 0
                fi
              ;;
              3)
                if [[ "$prev" == "mirror" ]]; then
                  COMPREPLY=($(compgen -W "$(__aptly_mirror_list)" -- ${cur}))
                  return 0
                fi
                if [[ "$prev" == "repo" ]]; then
                  COMPREPLY=($(compgen -W "$(__aptly_repo_list)" -- ${cur}))
                  return 0
                fi
              ;;
            esac
          ;;
          "diff")
            if [[ $numargs -eq 0 ]] && [[ "$cur" == -* ]]; then
              COMPREPLY=($(compgen -W "-only-matching" -- ${cur}))
              return 0
            fi

            if [[ $numargs -lt 2 ]]; then
              COMPREPLY=($(compgen -W "$(__aptly_snapshot_list)" -- ${cur}))
              return 0
            fi
          ;;
          "drop")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-force" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_snapshot_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "list")
            if [[ $numargs -eq 0 ]]; then
                COMPREPLY=($(compgen -W "-raw -sort=" -- ${cur}))
              return 0
            fi
          ;;
          "merge")
            if [[ $numargs -gt 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-latest" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_snapshot_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "pull")
            if [[ $numargs -eq 0 ]] && [[ "$cur" == -* ]]; then
              COMPREPLY=($(compgen -W "-all-matches -dry-run -no-deps -no-remove" -- ${cur}))
              return 0
            fi

            if [[ $numargs -lt 2 ]]; then
              COMPREPLY=($(compgen -W "$(__aptly_snapshot_list)" -- ${cur}))
              return 0
            fi
          ;;
          "filter")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-with-deps" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_snapshot_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "show")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-with-packages" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_snapshot_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "search")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-format= -with-deps" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_snapshot_list)" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "rename")
            if [[ $numargs -eq 0 ]]; then
              COMPREPLY=($(compgen -W "$(__aptly_snapshot_list)" -- ${cur}))
              return 0
            fi
          ;;
          "verify")
            if [[ $numargs -eq 0 ]]; then
              COMPREPLY=($(compgen -W "$(__aptly_snapshot_list)" -- ${cur}))
              return 0
            fi
          ;;
        esac
      ;;
      "publish")
        case "$subcmd" in
          "snapshot"|"repo")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-acquire-by-hash -batch -butautomaticupgrades= -component= -distribution= -force-overwrite -gpg-key= -keyring= -label= -notautomatic= -origin= -passphrase= -passphrase-file= -secret-keyring= -skip-contents -skip-signing" -- ${cur}))
              else
                if [[ "$subcmd" == "snapshot" ]]; then
                  COMPREPLY=($(compgen -W "$(__aptly_snapshot_list)" -- ${cur}))
                else
                  COMPREPLY=($(compgen -W "$(__aptly_repo_list)" -- ${cur}))
                fi
              fi
              return 0
            fi

            if [[ $numargs -eq 1 ]]; then
              COMPREPLY=($(compgen -W "$(__aptly_published_prefixes)" -- ${cur}))
              return 0
            fi
          ;;
          "list")
            if [[ $numargs -eq 0 ]]; then
                COMPREPLY=($(compgen -W "-raw" -- ${cur}))
              return 0
            fi
          ;;
          "update")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-batch -force-overwrite -gpg-key= -keyring= -passphrase= -passphrase-file= -secret-keyring= -skip-cleanup -skip-contents -skip-signing" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_published_distributions)" -- ${cur}))
              fi
              return 0
            fi

            if [[ $numargs -eq 1 ]]; then
              COMPREPLY=($(compgen -W "$(__aptly_prefixes_for_distribution $prev)" -- ${cur}))
              return 0
            fi
          ;;
          "switch")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-batch -force-overwrite -component= -gpg-key= -keyring= -passphrase= -passphrase-file= -secret-keyring= -skip-cleanup -skip-contents -skip-signing" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_published_distributions)" -- ${cur}))
              fi
              return 0
            fi

            if [[ $numargs -eq 1 ]]; then
              COMPREPLY=($(compgen -W "$(__aptly_prefixes_for_distribution $prev)" -- ${cur}))
              return 0
            fi

            if [[ $numargs -ge 2 ]]; then
              COMPREPLY=($(compgen -W "$(__aptly_snapshot_list)" -- ${cur}))
              return 0
            fi
          ;;
          "drop")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-force-drop -skip-cleanup" -- ${cur}))
              else
                COMPREPLY=($(compgen -W "$(__aptly_published_distributions)" -- ${cur}))
              fi
              return 0
            fi

            if [[ $numargs -eq 1 ]]; then
              COMPREPLY=($(compgen -W "$(__aptly_prefixes_for_distribution $prev)" -- ${cur}))
              return 0
            fi
          ;;
        esac
      ;;
      "package")
        case "$subcmd" in
          "search")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-format=" -- ${cur}))
              fi
              return 0
            fi
          ;;
          "show")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-with-files -with-references" -- ${cur}))
              fi
              return 0
            fi
          ;;
        esac
      ;;
      "serve")
        if [[ "$cur" == -* ]]; then
          COMPREPLY=($(compgen -W "-listen=" -- ${cur}))
          return 0
        fi
      ;;
      "graph")
        if [[ "$cur" == -* ]]; then
          COMPREPLY=($(compgen -W "-format= -output=" -- ${cur}))
          return 0
        fi
      ;;
      "api")
        case "$subcmd" in
          "serve")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-listen=" -- ${cur}))
              fi
              return 0
            fi
          ;;
        esac
      ;;
      "db")
        case "$subcmd" in
          "cleanup")
            if [[ $numargs -eq 0 ]]; then
              if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "-dry-run -verbose" -- ${cur}))
              fi
              return 0
            fi
          ;;
        esac
      ;;
    esac
} && complete -F _aptly aptly
