#!/bin/bash
# vim: ft=sh ts=2 sw=2 sts=2 et

# vpm - void package management utility for
# XBPS, the X Binary Package System
# Copyright (c) 2016-2020 Armin Jenewein - GitHub: @netzverweigerer
# For more information about XBPS, see:
# https://github.com/voidlinux/xbps
# 
# Released under the terms of the GNU general public license, version 3+
# see LICENSE file for license information.

# VPM color definitions
numcolorok=2
numcolorfail=1
numcolorlogo=5
numcolorheader=3
numcolortext=4
numcolorgray=2
numcolorpkgcount=8
numcolordarkgray=11
numcolorbrackets=6

getversion () {
  local fp=$(readlink -f "$0")
  (cd "${fp%/*}" && \
    git describe --all --debug --long --tags 2>/dev/null) || echo "UNKNOWN"
}

version=$(getversion)
progname=${0##*/}
verbose=false

# enable or disable colors based on the argument given, i.e.:
# setcolors on   # colors on
# setcolors off  # colors off
# setcolors auto # colors on or off depending on environment
declare -A COLORS
setcolors () {
  local opt=$1

  # determine if colors should be enabled or not
  if [[ $opt == auto ]]; then
    # if stdout is a TTY and the TERM looks like it supports color enable colors
    if [[ -t 1 && $TERM == *color* ]]; then
      opt='on'
    else
      opt='off'
    fi
  fi

  case "$opt" in
    on)
      local i
      for i in {1..11}; do
        if [[ -n ${COLORS[$i]} ]]; then
          continue
        fi
        COLORS[$i]=$(tput setaf "$i")
      done
      colorbrackets=${COLORS[$numcolorbrackets]}
      colordarkgray=${COLORS[$numcolordarkgray]}
      colorfail=${COLORS[$numcolorfail]}
      colorgray=${COLORS[$numcolorgray]}
      colorheader=${COLORS[$numcolorheader]}
      colorlogo=${COLORS[$numcolorlogo]}
      colorok=${COLORS[$numcolorok]}
      colorpkgcount=${COLORS[$numcolorpkgcount]}
      colortext=${COLORS[$numcolortext]}
      colorreset=$(tput sgr0)
    ;;
    off)
      colorbrackets=
      colordarkgray=
      colorfail=
      colorgray=
      colorheader=
      colorlogo=
      colorok=
      colorpkgcount=
      colortext=
      colorreset=
      unset COLORS
      declare -A COLORS
    ;;
    *)
      rmsg 255 "unknown color option: '$opt'"
      exit 255
    ;;
  esac
}

# print the logo with brackets colorized
getlogo () {
  printf '%s[%s%s%s]%s' \
    "$colorbrackets" \
    "$colorlogo" "$progname" \
    "$colorbrackets" \
    "$colorreset"
}

# prints a message (with vpm-prefix)
msg () {
  local logo=$(getlogo)

  echo "$logo" "$colortext" "$@" "$colorreset"
}

# rmsg - same (but colorized based on return status passed via $1)
rmsg () {
  local code=$1
  shift

  local logo=$(getlogo)
  local statuscolor

  if ((code == 0)); then
    statuscolor=$colorok
  else
    statuscolor=$colorfail
  fi

  echo "$logo" "$statuscolor" "$@" "$colorreset"
}

banner () {
  echo -n "$colorlogo"
  echo ' __ ___ __ _ __  '

  printf " \\ V / '_ \\ '  \ "
  echo -n "$colorgray"
  echo "  $progname - void package management utility for XBPS"
  echo -n "$colorlogo"
  echo -n '  \_/| .__/_|_|_|'
  echo -n "$colorgray"
  echo '  GitHub: https://github.com/netzverweigerer/vpm'
  echo -n "$colorlogo"
  echo '     |/          '
  echo '     ´          '
  echo -n "$colorreset"
}

version () {
  banner
  msg "$progname - Version: $version"
  msg "Copyright (c) 2016 Armin Jenewein <a@m2m.pm> (GPLv3+)"
  msg "XBPS version: $(xbps-query -v --version | sed 's/GIT: UNSET//')"
}

# check if we have UID 0, exit otherwise
rootcheck () {
  if [[ $EUID -gt 0 ]]; then
    msg "ERROR: $progname: This operation needs super-user privileges. Exiting."
    exit 255
  fi
}

t () {
  if [[ -n $show_translations ]]; then
    tput setaf 242
    echo '                             ' "$@"
    echo
    tput setaf 109
  fi
}

usage () {
  echo
  version
  echo
  echo -n "$colorheader"
  echo "USAGE: "
  echo -n "$colorgray"
  echo "$progname [OPTIONS] [SUBCOMMANDS] [<ARGS>]"
  echo
  echo -n "$colorheader"
  echo "OPTIONS: "
  echo -n "$colorgray"
  echo "--color=<yes|no|auto>        - Enable/Disable colorized output (default: auto)"
  echo "--help                       - (same as: help)"
  echo "--help-pager                 - (same as: helppager)"
  echo "--show-translations          - Show XBPS command translations for $progname sub-commands"
  echo "--verbose                    - Verbose mode (shows XBPS command translations during execution)"
  echo
  echo -n "$colorheader"
  echo "SUBCOMMANDS: "
  echo -n "$colorgray"
  echo "sync                         - Synchronize remote repository data"
  t "xbps-install -S"
  echo "update (up)                  - Update the system"
  t "xbps-install -Sduv"
  echo "listrepos (lr)               - List configured repositories"
  echo "repolist (rl)                - Alias for listrepos"
  t "xbps-query -v -L"
  echo "addrepo (ar) <ARGS>          - Add an additional repository"
  t "xbps-install <ARGS>"
  echo "info <pkg>                   - Show information about <package>"
  t "xbps-query-v -R"
  echo "filelist (fl) <pkg>          - Show file-list of <package>"
  t "xbps-query -v -R -f"
  echo "deps <pkg>                   - Show dependencies for <package>"
  t "xbps-query -v -R -x"
  echo "reverse (rv) <pkg>           - Show reverse dependendies of <package> (see man xbps-query)"
  t "xbps-query -v -R -X"
  echo "search (s) <name>            - Search for package by <name>"
  t "xbps-query -v -Rs"
  echo "searchfile (sf) <file>       - Search for package containing <file> (local)"
  t "xbps-query -v -o \"*/$1\""
  echo "list (ls)                    - List installed packages"
  t "xbps-query -v -l"
  echo "install (i) <pkg(s)>         - Install <package(s)>"
  t "xbps-install -S"
  echo "devinstall (di) <pkg(s)>     - Install <package> (and corresponding <package>-devel package(s))"
  t "xbps-install -S <package> <package>-devel"
  echo "listalternatives (la)        - List alternative candidates"
  t "xbps-alternatives -l"
  echo "setalternative (sa) <pkg(s)  - Set alternative for <package>"
  t "xbps-alternatives -s"
  echo "reconfigure (rc) <pkg>       - Re-configure installed <package>"
  t "xbps-reconfigure -v"
  echo "forceinstall (fi) <pkg(s)>   - Force installation of <package(s)>"
  t "xbps-install -f"
  echo "remove <package(s))          - Remove <package(s)> from the system"
  t "xbps-remove -v "
  echo "removerecursive <pkg(s)>     - Recursively remove package(s) (and its dependencies)"
  t "xbps-remove -v -R"
  echo "cleanup (cl)                 - Clean up cache directory"
  t "xbps-remove -v -O"
  echo "autoremove (ar)              - Remove orphaned packages"
  t "xbps-remove -v -O"
  echo "whatprovides (wp) <file>     - Search for package containing <file>"
  t "xlocate <pkg>"
  echo "help                         - Show usage information"
  echo "helppager (hp)               - Show usage information (will pipe output to less/more)"
  echo
  echo -n "$colorheader"
  echo "XBPS COMPATIBILITY COOLNESS:"
  echo -n "$colorgray"
  f=(/usr/sbin/xbps-*)
  echo "$progname also understands all unknown XBPS sub-commands, too:"
  echo -n "Example: "
  selected=${f[$RANDOM % ${#f[@]}]}
  echo "$progname ${selected##*-} <ARGS> - see also: /usr/sbin/xbps-*"
  echo
  echo -n "$colorreset"
}

setcolors auto
case "$1" in
  --color=true|--color=yes|--color=on)
    setcolors on
    shift
  ;;
  --color=auto)
    setcolors auto
    shift
  ;;
  --color=false|--color=off|--color=no)
    setcolors off
    shift
  ;;
  --verbose=true)
    shift
    verbose=true
  ;;
  --show-translations)
    shift
    show_translations=1
  ;;
  --help)
    shift
    usage
    exit 255
  ;;
  --help-pager)
    shift
    "$0" --color=off --help | less
  ;;
  --*)
    msg "Unknown option: $1 (try: $progname --help)"
    exit 1
  ;;
esac

if [[ "$1" == "" ]]; then
  usage
  exit 0
fi

arg=$1

if [[ "$arg" =~ --.* ]]; then
  b=${arg:2}
  arg=$b
fi

case "$arg" in
  info|in)
    shift
    msg "(xbps-query -v -R $@):"
    xbps-query -v -R "$@"
    ret=$?
    rmsg "$ret" "Execution finished (xbps-query -v -R $@), return code was: $ret"
    exit "$ret"
  ;;

  filelist|fl|listfiles)
    shift
    xbps-query -v -R -f "$@"
    ret=$?;
    if [[ $verbose == "true" ]]; then
      rmsg "$ret" "Execution finished (xbps-query -v -R -f \"*/$1\"), return code was: $ret"
    fi
    exit "$ret"
  ;;

  deps|dep|dependencies)
    shift
    xbps-query -v -R -x "$@"
    ret=$?
    rmsg "$ret" "Execution finished (xbps-query -v -R -x \"*/$1\"), return code was: $ret"
    exit "$ret"
  ;;

  reverse|rv)
    shift
    msg "Reverse dependencies for $@ (xbps-query -v -R $@):"
    xbps-query -v -R -X "$@"
    ret=$?
    msg "$ret" "Execution finished (xbps-query -v -R $@), return code was: $ret"
    exit "$ret"
  ;;

  searchfile|sf)
    shift
    msg "searchfile (xbps-query -v -o \"*/$1\"):"
    xbps-query -v -o "*/$1"
    ret=$?
    msg "$ret" "Execution finished (xbps-query -v -o \"*/$1\"), return code was: $ret"
    exit $ret
  ;;

  remotesearchfile|rsf)
    shift
    msg "remotesearchfile (xbps-query -R -v -o \"*/$1\"):"
    xbps-query -R -v -o "*/$1"
    ret=$?
    msg "$ret" "Execution finished (xbps-query -R -v -o \"*/$1\"), return code was: $ret"
    exit "$ret"
  ;;

  list|ls)
    shift
    msg "Installed packages: "

    count=0
    while read -r _ pkg _; do
      ((count++))
      pkgname=${pkg%-*}
      version=${pkg##*-}

      printf '%s%d %s%s %s (%s%s%s) [%s%s%s]%s\n' \
        "$colorpkgcount" "$count" \
        "$colortext" "$pkgname" \
        "$colorbrackets" \
        "$colorgray" "$version" \
        "$colorbrackets" \
        "$colordarkgray" "$pkg" \
        "$colorbrackets" \
        "$colorreset"
    done < <(xbps-query -v -l)
  ;;

  listalternative|listalternatives|la)
    xbps-alternatives -l "$@"
    ret=$?
    rmsg "$ret" "xbps-alternatives return code: $ret (xbps-alternatives -l $@)"
  ;;

  setalternative|setalternatives|sa)
    shift
    rootcheck
    xbps-alternatives -s "$@"
    ret=$?
    rmsg "$ret" "xbps-alternatives return code: $ret (xbps-alternatives -s $@)"
  ;;

  repolist|listrepos|rl|lr)
    msg "Configured repositories (xbps-query -v -L): "
    xbps-query -v -L
    ret=$?
    rmsg "$ret" "[xbps-query -v -L] return code: $ret"
    shift
    echo
    msg "Available sub-repositories (xbps-query -v -Rs void-repo): "
    xbps-query -v -Rs void-repo
    ret=$?
    rmsg "$ret" "[xbps-query -v -Rs void-repo] return code: $ret"
    shift
    echo
    msg "Use \"$progname addrepo <repository>\" to add a sub-repository."
    echo
  ;;

  addrepo|ar)
    shift
    rootcheck
    for repo in "$@"; do
      msg "Adding repository: $repo"
      xbps-install "$1"
      ret=$?
      rmsg "$ret" "[xbps-install $arg] return code: $ret"
      msg "Synchronizing remote repository data (xbps-install -S): "
      xbps-install -S
      ret=$?
      rmsg "$ret" "[xbps-install -S] return code: $ret"
      shift
    done
    ;;

  sync|sy)
    shift
    rootcheck
    msg "Synchronizing remote repository data: (xbps-install -S):"
    xbps-install -S
    ret=$?
    rmsg "$ret" "[xbps-install -S] return code: $ret"
  ;;

  install|i)
    shift
    rootcheck
    if [[ "$#" -lt 1 ]]; then
      msg "ERROR: install: argument missing, try --help."
      exit 1
    fi
    msg "Installing packages: $@ (xbps-install -S $@) ..."
    xbps-install -S "$@"
    ret=$?
    rmsg "$ret" "[xbps-install -S $@] return code: $ret"
  ;;

  yesinstall)
    shift
    rootcheck
    if [[ "$#" -lt 1 ]]; then
      msg "ERROR: install: argument missing, try --help."
      exit 1
    fi
    msg "Installing packages: $@ (xbps-install -S $@) ..."
    xbps-install -y -S "$@"
    ret=$?
    rmsg "$ret" "[xbps-install -S $@] return code: $ret"
  ;;

  devinstall)
    shift
    rootcheck
    if [[ "$#" -lt 1 ]]; then
      msg "ERROR: devinstall: argument missing, try --help."
      exit 1
    fi
    args=("$@")
    msg "devinstall: Packages will be installed one-by-one"
    msg "Use \"forceinstall\" to override this if you know what you're doing."
    msg "(Note: forceinstall won't install -devel packages)"
    for arg in "${args[@]}"; do
      let count=count+1
      msg "Installing package: $arg (xbps-install -S $arg) ..."
      xbps-install -S "$arg"
      ret=$?
      rmsg "$ret" "[xbps-install -S $arg] return code: $ret"
      msg "installing devel package (${arg}-devel):"
      xbps-install -S "${arg}-devel"
      ret=$?
      rmsg "$ret" "[xbps-install -S ${arg}-devel] return code: $ret"
    done
  ;;

  forceinstall|fi)
    shift
    rootcheck
    msg "Force-Installing Package(s): $@ (xbps-install -Sf $@)"
    xbps-install -Sf "$@"
    ret=$?
    rmsg "$ret" "[xbps-install -Sf ${@}] return code: $ret"
  ;;

  remove|rm)
    shift
    rootcheck
    msg "Removing package(s): $@ (xbps-remove -v $@)"
    xbps-remove -v "$@"
    ret=$?
    rmsg "$ret" "[xbps-remove -v ${@}] return code: $ret"
  ;;

  removerecursive|rr)
    shift
    rootcheck
    msg "Removing package(s) recursively: $@ (xbps-remove -v -R $@)"
    xbps-remove -v -R "$@"
    ret=$?
    rmsg "$ret" "[xbps-remove -v -R ${@}] return code: $ret"
  ;;

  reconfigure|rc)
    shift
    rootcheck
    msg "reconfigure: Re-configuring package(s) (xbps-reconfigure -v $@):"
    xbps-reconfigure -v "$@"
    ret=$?
    rmsg "$ret" "[xbps-reconfigure -v ${@}] return code: $ret"
  ;;

  autoremove|ar)
    shift
    rootcheck
    msg "autoremove: Removing orphaned packages (xbps-remove -v -o)"
    xbps-remove -v -o
    ret=$?
    rmsg "$ret" "[xbps-remove -v -o] return code: $ret"
  ;;

  update|upgrade|up)
    shift
    rootcheck
    msg "Running system update (xbps-install -Suv)"
    xbps-install -Suv
    ret=$?
    if [[ $ret == 16 ]]; then
      msg "Updating xbps (xbps-install -u xbps)"
      xbps-install -u xbps
      ret2=$?
      rmsg "$ret2" "[xbps-install -u xbps] return code: $ret2"
      exit 0 
    fi
    rmsg "$ret" "[xbps-install -Suv] return code: $ret"
  ;;

  search|s)
    shift
    msg "Searching for: $@ (xbps-query -v -Rs $@)"
    xbps-query -v -Rs "$@"
    ret=$?
    rmsg "$ret" "[xbps-query -v -Rs $@] return code: $ret"
  ;;

  cleanup|clean|cl)
    msg "Cleaning up packages (will remove orphaned packages) (xbps-remove -v -O $@)"
    shift
    rootcheck
    xbps-remove -v -O "$@"
    ret=$?
    rmsg "$ret" "[xbps-remove -v -O $@] return code: $ret"
  ;;

  h|help|-h|--help)
    usage
  ;;

  helppager|help-pager|hp)
    if hash less >/dev/null 2>&1; then
      "$0" --color=off help | less
    else
      "$0" --color=off help | more
    fi
  ;;

  whatprovides|wp)
    shift
    if hash xlocate >/dev/null 2>&1; then
      # set -x
      # xlocate -S "$@"
      msg "relaying to: \"xlocate $@\" - use xlocate -S to (re-)build cached DB."
      xlocate "$@"
    else
      rmsg 255 "xlocate not found. Try installing the xtools package."
    fi
  ;;

  ''|*)
    a="$1"
    if hash "xbps-${a}" >/dev/null 2>&1; then
      shift
      # xbps-<subcommand> found
      msg "relaying to XBPS: xbps-$a $@"
      "xbps-$a" "$@"
      ret=$?
      rmsg "$ret" "xbps-$a $@ return code: $ret"
    else
      rmsg 255 "Unrecognized $progname subcommand: $1 (and xbps-$1 does not exist) - Try: $progname help"
      echo
      exit 1
    fi
  ;;

esac

exit 0
