#!/bin/bash
#
# Copyright (C) Matthew Bruenig <matthewbruenig@gmail.com>
# Copyright (C) Gavin Lloyd <gavinhungry@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

[[ $PACMAN ]] || PACMAN="pacman"

# set tmpfile stuff, clean tmpdir
tmpdir="${TMPDIR:-/tmp}/packertmp-$UID"
rm -rf "$tmpdir" &>/dev/null
mkdir -p "$tmpdir"

makepkgconf='/etc/makepkg.conf'
usermakepkgconf="$HOME/.makepkg.conf"
pacmanconf='/etc/pacman.conf'

AUR_DOMAIN=aur.archlinux.org
AUR_VERSION=5

RPCURL="https://${AUR_DOMAIN}/rpc.php?v=${AUR_VERSION}&type"
PKGURL="https://${AUR_DOMAIN}"
PKGBUILDURL="https://${AUR_DOMAIN}/cgit/aur.git/plain/PKGBUILD?h"

if [[ -t 1 && ! $COLOR = "NO" ]]; then
  COLOR1='\e[1;39m'
  COLOR2='\e[1;32m'
  COLOR3='\e[1;35m'
  COLOR4='\e[1;36m'
  COLOR5='\e[1;34m'
  COLOR6='\e[1;33m'
  COLOR7='\e[1;31m'
  COLOR8='\e[0;33m'
  ENDCOLOR='\e[0m'
  S='\\'
fi
_WIDTH="$(stty size | cut -d ' ' -f 2)"

# nop makepkg functions as workaround for bad PKGBUILDs
plain() {
  return 0
}
msg() {
  return 0
}
msg2() {
  return 0
}
warning() {
  return 0
}
error() {
  return 0
}

trap ctrlc INT
ctrlc() {
  echo
  exit 130
}

err() {
  echo -e "$1"
  exit 1
}

usage() {
  echo 'usage: packer [option] [package] [package] [...]'
  echo
  echo '    -S           - installs package'
  echo '    -Sd[d]       - skips dependency version checks'
  echo '    -Syu|-Su     - updates all packages, also takes -uu and -yy options'
  echo '    -Ss|-Ssq     - searches for package'
  echo '    -Si          - outputs info for package'
  echo '    -G           - download and extract aur tarball only'
  echo
  echo '    --quiet      - only output package name for searches'
  echo '    --force      - bypass file conflict checks'
  echo '    --ignore     - takes a comma-separated list of packages to ignore'
  echo '    --noconfirm  - do not prompt for any confirmation'
  echo '    --noedit     - do not prompt to edit files'
  echo '    --quickcheck - check for updates and exit'
  echo '    --aur, -a    - include AUR actions'
  echo '    --auronly    - only check the AUR (implies --aur)'
  echo '    --devel      - update devel packages during -Su'
  echo '    --skipinteg  - when using makepkg, do not check md5s'
  echo '    --preview    - edit pkgbuild before sourcing'
  echo '    --help       - outputs this message'
  exit
}

# Called whenever anything needs to be run as root ($@ is the command)
runasroot() {
  if [[ $UID -eq 0 ]]; then
    "$@"
  elif sudo -v &>/dev/null && sudo -l "$@" &>/dev/null; then
    sudo -E "$@"
  else
    echo -n "root "
    su -c "$(printf '%q ' "$@")"
  fi
}

# Source makepkg.conf file
sourcemakepkgconf() {
  . "$makepkgconf"
  [[ -r "$usermakepkgconf" ]] && . "$usermakepkgconf"
}

# Parse IgnorePkg and --ignore, put in globally accessible ignoredpackages array
getignoredpackages() {
  IFS=',' read -ra ignoredpackages <<< "$ignorearg"
  ignoredpackages+=( $(grep '^ *IgnorePkg' "$pacmanconf" | cut -d '=' -f 2-) )
}

# Checks to see if $1 is an ignored package
isignored() {
  [[ " ${ignoredpackages[@]} " =~ " $1 " ]]
}

# Tests whether $1 exists on the aur
existsinaur() {
  rpcinfo "$1"
  [[ "$(jshon -Qe resultcount -u < "$tmpdir/$1.info")" != "0" ]]
}

# Tests whether $1 exists in pacman
existsinpacman() {
  pacman -Si -- "$1" &>/dev/null
}

# Tests whether $1 is provided in pacman, sets globally accessibly providepkg var
providedinpacman() {
  unset providepkg
  IFS=$'\n' read -rd '' -a providepkg < <(pacman -Ssq -- "^$1$")
  [[ -n $providepkg ]]
}

# Tests whether $1 exists in a pacman group
existsinpacmangroup() {
  [[ $($PACMAN -Sgq "$1") ]]
}

# Tests whether $1 exists locally
existsinlocal() {
  pacman -Qq -- "$1" &>/dev/null
}

# Scrapes the aur deps from PKGBUILDS and puts in globally available dependencies array
scrapeaurdeps() {
  pkginfo "$1" "$preview"
  . "$tmpdir/$1.PKGBUILD" 2> /dev/null
  IFS=$'\n'
  depends_arch=depends_$arch[*]
  dependencies=( $(echo -e "${depends[*]}\n${!depends_arch}\n${makedepends[*]}" | sed -e 's/=.*//' -e 's/>.*//' -e 's/<.*//'| sort -u) )
  unset IFS
}

# Finds dependencies of package $1
# Sets pacmandeps and aurdeps array, which can be accessed globally after function runs
finddeps() {
  # loop through dependencies, if not installed, determine if pacman or aur deps
  pacmandeps=()
  aurdeps=()
  scrapeaurdeps "$1"
  missingdeps=( $($PACMAN -T "${dependencies[@]}") )
  while [[ $missingdeps ]]; do
    checkdeps=()
    for dep in "${missingdeps[@]}"; do
      if [[ " $1 ${aurdeps[@]} ${pacmandeps[@]} " =~ " $dep " ]];  then
        continue
      fi
      if existsinpacman "$dep"; then
        pacmandeps+=("$dep")
      elif existsinaur "$dep"; then
        if [[ $aurdeps ]]; then
          aurdeps=("$dep" "${aurdeps[@]}")
        else
          aurdeps=("$dep")
        fi
        checkdeps+=("$dep")
      elif providedinpacman "$dep"; then
        pacmandeps+=("$providepkg")
      else
        [[ $option = "install" ]] &&  err "Dependency \`$dep' of \`$1' does not exist."
        echo "Dependency \`$dep' of \`$1' does not exist."
        return 1
      fi
    done
    missingdeps=()
    for dep in "${checkdeps[@]}"; do
      scrapeaurdeps "$dep"
      for depdep in "${dependencies[@]}"; do
        [[ $($PACMAN -T "$depdep") ]] && missingdeps+=("$depdep")
      done
    done
  done
  return 0
}

# Displays a progress bar ($1 is numerator, $2 is denominator, $3 is candy/normal)
aurbar() {
  # Delete line
  printf "\033[0G"

  # Get vars for output
  beginline=" aur"
  beginbar="["
  endbar="]"
  perc="$(($1*100/$2))"
  width="$(stty size)"
  width="${width##* }"
  infolen="$(($width*6/10))"
  [ $infolen -lt 50 ] && infolen=50

  charsbefore="$((${#beginline}+${#1}+${#2}+3))"
  spaces="$(($infolen-$charsbefore))"
  barchars="$(($width-$infolen-${#beginbar}-${#endbar}-6))"
  hashes="$(($barchars*$perc/100))"
  dashes="$(($barchars-$hashes))"

  # Print output
  printf "$beginline %${spaces}s$1  $2 ${beginbar}" ""

  # ILoveCandy
  if [[ $3 = candy ]]; then
    for ((n=1; n<$hashes; n++)); do
      if (( (n==($hashes-1)) && ($dashes!=0) )); then
        (($n%2==0)) && printf "\e[1;33mc\e[0m" || printf "\e[1;33mC\e[0m"
      else
        printf "-"
      fi
    done
    for ((n=1; n<$dashes; n++)); do
      N=$(( $n+$hashes ))
      (($hashes>0)) && N=$(($N-1))
      (($N%3==0)) && printf "o" || printf " "
    done
  else
    for ((n=0; n<$hashes; n++)); do
      printf "#"
    done
    for ((n=0; n<$dashes; n++)); do
      printf "-"
    done
  fi
  printf "%s%4s%%\r" ${endbar} ${perc}
}

rpcinfo() {
  if ! [[ -f "$tmpdir/$1.info" ]]; then
    curl -LfGs --data-urlencode "arg=$1" "${RPCURL}=info" > "$tmpdir/$1.info"
  fi
}

pkglink() {
  rpcinfo $1
  echo "${PKGURL}$(jshon -Q -e results -a -e URLPath -u < "$tmpdir/$1.info")"
}

# downloads pkgbuild ($1), edits if $2 is set
pkginfo() {
  if ! [[ -f "$tmpdir/$1.PKGBUILD" ]]; then
    curl -Lfs "${PKGBUILDURL}=$1" > "$tmpdir/$1.PKGBUILD"
    if [[ $2 ]]; then
      # rename for syntax highlighting
      ln -sf "$tmpdir/$1.PKGBUILD" "$tmpdir/PKGBUILD"
      confirm_edit "${COLOR1}Edit $1 PKGBUILD? [y/N]${ENDCOLOR} " "$tmpdir/PKGBUILD"
      rm -f "$tmpdir/PKGBUILD"
    fi
  fi
}

# Checks if package is newer on aur ($1 is package name, $2 is local version)
aurversionisnewer() {
  rpcinfo "$1"
  unset aurversion
  if existsinaur "$1"; then
    aurversion="$(jshon -Q -e results -a -e Version -u < "$tmpdir/$1.info")"
    if [[ "$(LC_ALL=C vercmp "$aurversion" "$2")" -gt 0  ]]; then
      return 0
    fi
  fi
  return 1
}

isoutofdate() {
  rpcinfo "$1"
  [[ "$(jshon -Q -e results -a -e OutOfDate -u < "$tmpdir/$1.info")" = "1" ]]
}

installedline() {
  aurpkg=$(echo $1 | cut -d' ' -f1)
  aurver=$(echo $1 | cut -d' ' -f2)
  if [ ! -z $aurpkg -a ! -z $aurver ] && existsinlocal "$aurpkg"; then
    localversion="$($PACMAN -Qs "${aurpkg}$" | grep -F "local/$aurpkg" | cut -d ' ' -f 2)"
    [ "$aurver" != "$localversion" ] \
      && echo -n " ${COLOR4}[installed: $localversion]${ENDCOLOR}" \
      || echo -n " ${COLOR4}[installed]${ENDCOLOR}"
  fi
}

outofdateline() {
  ood=$(echo $1 | cut -d' ' -f5)
  [ "$ood" != "null" ] && echo -n " ${COLOR7}(out-of-date)${ENDCOLOR}"
}

# $1 is prompt, $2 is file
confirm_edit() {
  if [[ (! -f "$2") || "$noconfirm" || "$noedit" ]]; then
    return
  fi
  echo -en "$1"
  if proceed_explicit; then
    ${EDITOR:-vi} "$2"
  fi
}

# Installs packages from aur ($1 is package, $2 is dependency or explicit)
aurinstall() {
  echo -e "Installing AUR package: $1"

  dir="${TMPDIR:-/tmp}/packerbuild-$UID/$1"
  sourcemakepkgconf

  # Prepare the installation directory
  # If there is an old directory and aurversion is not newer, use old directory
  if . "$dir/$1/PKGBUILD" &>/dev/null && ! aurversionisnewer "$1" "$pkgver-$pkgrel"; then
    cd "$dir/$1"
  else
    [[ -d "$dir" ]] && rm -rf "$dir"
    mkdir -p "$dir"
    cd "$dir"
    curl -Lfs "$(pkglink $1)" > "$1.tar.gz"
    mkdir "$1"
    tar xf "$1.tar.gz" -C "$1" --strip-components=1
    cd "$1"
    if [[ $preview &&  -s "$tmpdir/$1.PKGBUILD" ]]; then
      cp "$tmpdir/$1.PKGBUILD" PKGBUILD
    fi
    # customizepkg
    if [[ -f "/etc/customizepkg.d/$1" ]] && type -t customizepkg &>/dev/null; then
      echo "Applying customizepkg instructions..."
      customizepkg --modify
    fi
  fi

  # Allow user to edit PKGBUILD
  confirm_edit "${COLOR1}Edit $1 PKGBUILD? [y/N]${ENDCOLOR} " PKGBUILD
  if ! [[ -f PKGBUILD ]]; then
    err "No PKGBUILD found in directory."
  fi

  # Allow user to edit .install
  unset install
  unset pkgname

  . PKGBUILD
  confirm_edit "${COLOR1}Edit $install? [y/N]${ENDCOLOR} " "$install"

  [[ $(uname -m) == arm* ]] && MAKEPKGOPTS+=("--ignorearch")

  # Installation (makepkg and pacman)
  rm -f *$PKGEXT
  if [[ $UID -eq 0 ]]; then
    id pacman &> /dev/null || useradd pacman -rd /var/empty
    chown -R pacman:pacman .
    su pacman -c "makepkg $MAKEPKGOPTS -f"
  else
    makepkg $MAKEPKGOPTS -f
  fi

  [[ $? -ne 0 ]] && echo "The build failed." && return 1
  pkgtarfiles=""
  for i in "${pkgname[@]}"; do
    pkgtarfiles="$pkgtarfiles $i-*$PKGEXT"
  done
  pkgtarfiles=$(echo $pkgtarfiles | tr ' ' '\n' | sort -u)
  if  [[ $2 = dependency ]]; then
    runasroot $PACMAN ${PACOPTS[@]} --asdeps -U $pkgtarfiles
  elif [[ $2 = explicit ]]; then
    runasroot $PACMAN ${PACOPTS[@]} -U $pkgtarfiles
  fi

  echo
}

# Goes through all of the install tests and execution ($@ is packages to be installed)
installhandling() {
  packageargs=("$@")
  getignoredpackages
  sourcemakepkgconf
  # Figure out all of the packages that need to be installed
  for package in "${packageargs[@]}"; do
    # Determine whether package is in pacman repos
    if ! [[ $auronly ]] && existsinpacman "$package"; then
      pacmanpackages+=("$package")
    elif ! [[ $auronly ]] && existsinpacmangroup "$package"; then
      pacmanpackages+=("$package")
    elif existsinaur "$package"; then
      if finddeps "$package"; then
        # here is where dep dupes are created
        aurpackages+=("$package")
        aurdepends=("${aurdeps[@]}" "${aurdepends[@]}")
        pacmandepends+=("${pacmandeps[@]}")
      fi
    else
      err "Package \`$package' does not exist."
    fi
  done

  # Check if any aur target packages are ignored
  for package in "${aurpackages[@]}"; do
    if isignored "$package"; then
      echo -ne "${COLOR5}:: ${COLOR1}$package is in IgnorePkg/IgnoreGroup. Install anyway?${ENDCOLOR} [Y/n] "
      if [[ -z "$noconfirm" && $(! proceed) ]]; then
        continue
      fi
    fi
    aurtargets+=("$package")
  done

  # Check if any aur dependencies are ignored
  for package in "${aurdepends[@]}"; do
    if isignored "$package"; then
      echo -ne "${COLOR5}:: ${COLOR1}$package is in IgnorePkg/IgnoreGroup. Install anyway?${ENDCOLOR} [Y/n] "
      if [[ -z "$noconfirm" && $(! proceed) ]]; then
          echo "Unresolved dependency \`$package'"
          unset aurtargets
          break
      fi
    fi
  done

  # First install the explicit pacman packages, let pacman prompt
  if [[ $pacmanpackages ]]; then
    runasroot $PACMAN "${PACOPTS[@]}" -S -- "${pacmanpackages[@]}"
    echo
  fi
  if [[ -z $aurtargets ]]; then
    exit
  fi
  # Test if aurpackages are already installed; echo warning if so
  for pkg in "${aurtargets[@]}"; do
    if existsinlocal "$pkg"; then
      localversion="$($PACMAN -Qs "${pkg}$" | grep -F "local/$pkg" | cut -d ' ' -f 2)"
      if ! aurversionisnewer "$pkg" "$localversion"; then
        echo -e "${COLOR6}warning:$ENDCOLOR $pkg-$localversion is up to date -- reinstalling"
      fi
    fi
  done

  # Echo warning if packages are out of date
  for pkg in "${aurtargets[@]}" "${aurdepends[@]}"; do
    if isoutofdate "$pkg"; then
      echo -e "${COLOR6}warning:$ENDCOLOR $pkg is flagged out of date"
    fi
  done

  # remove duplicates
  for I in $(seq 0 ${#aurtargets[@]}); do
    for J in $(seq 0 $I); do
      [ $I -ne $J ] && [ "x${aurtargets[$I]}" == "x${aurtargets[$J]}" ] && unset aurtargets[$J]
    done

    for K in $(seq 0 ${#aurdepends[@]}); do
      [ "x${aurtargets[$I]}" == "x${aurdepends[$K]}" ] && unset aurdepends[$K]
    done
  done

  # Prompt for aur packages and their dependencies
  echo
  if [[ $pacmandepends ]]; then
    IFS=$'\n' read -rd '' -a pacmandepends < \
      <(printf "%s\n" "${pacmandepends[@]}" | sort -u)
    echo -e "${COLOR6}Targets (${#pacmandepends[@]}):${ENDCOLOR} ${pacmandepends[@]}"
  fi
  if [[ $aurdepends ]]; then
    num="$((${#aurdepends[@]}+${#aurtargets[@]}))"
    echo -e "${COLOR4}AUR ($num):${ENDCOLOR} ${aurdepends[@]} ${aurtargets[@]}"
  else
    echo -e "${COLOR4}AUR ($((${#aurtargets[@]}))):${ENDCOLOR} ${aurtargets[@]}"
  fi

  # Prompt to proceed
  echo -en "\nProceed with installation? [Y/n] "
  if ! [[ $noconfirm ]]; then
    proceed || exit
  else
    echo
  fi

  # Install pacman dependencies
  if [[ $pacmandepends ]]; then
    runasroot $PACMAN --noconfirm --asdeps -S -- "${pacmandepends[@]}" || err "Installation failed."
    echo
  fi

  # Install aur dependencies
  if [[ $aurdepends ]]; then
    for dep in "${aurdepends[@]}"; do
      aurinstall "$dep" "dependency"
    done
  fi

  # Install the aur packages
  for package in "${aurtargets[@]}"; do
    scrapeaurdeps "$package"
    if pacman -T "${dependencies[@]}" &>/dev/null; then
      aurinstall "$package" "explicit"
    else
      echo "Dependencies for \`$package' are not met, not building..."
    fi
  done
}

run_quick_check() {
  bigurl="${RPCURL}=multiinfo"

  for p in $($PACMAN -Qqm); do
    bigurl="$bigurl&arg\[\]=$p"
  done
  parsed_aur="$(curl -s "$bigurl" | \
    jshon -e results -a -e Name -u -p -e Version -u | \
    sed 's/^$/-/' | paste -s -d '\t\n' | sort)"
  packages="$(expac -Q '%n\t%v' | sort)"
  comm -23 <(echo "$parsed_aur") <(echo "$packages") | cut -f 1
  if [[ $auronly == 1 ]]; then
    return
  fi
  # see https://mailman.archlinux.org/pipermail/pacman-dev/2011-October/014673.html
  # (note to self, get that merged already...)
  if [[ -z $CHECKUPDATE_DB ]]; then
    CHECKUPDATE_DB="${TMPDIR:-/tmp}/checkup-db-${USER}/"
  fi
  eval $(awk '/DBPath/ {print $1$2$3}' $pacmanconf)
  DBPath="${DBPath:-/var/lib/pacman/}"
  mkdir -p "$CHECKUPDATE_DB"
  ln -s "${DBPath}/local" "$CHECKUPDATE_DB" &> /dev/null
  fakeroot pacman -Sqy --dbpath "$CHECKUPDATE_DB" &> /dev/null
  pacman -Qqu --dbpath "$CHECKUPDATE_DB" 2> /dev/null
}

# proceed with installation prompt
proceed() {
  read -n 1
  echo
  case "$REPLY" in
    'Y'|'y'|'') return 0 ;;
    *)          return 1 ;;
  esac
}

proceed_explicit() {
  read -n 1
  echo
  case "$REPLY" in
    'Y'|'y') return 0 ;;
    *)       return 1 ;;
  esac
}

# process busy loop
nap() {
  while (( $(jobs | wc -l) >= 512 )); do
    jobs > /dev/null
  done
}

# Argument parsing
[[ $1 ]] || usage
if [[ $1 != -* ]]; then
  $PACMAN "$@"
  exit $?
fi

packageargs=()
while [[ $1 ]]; do
  case "$1" in
    -I) interactive=1 ;;
    -R* | -D* | -U* | -Sc*)
      runasroot $PACMAN "$@"
      exit $?
    ;;
    -S*)
      [[ $1 =~ 'a' ]] && incaur='1'
      case "${1/a/}" in
        '-S') option=install ;;
        '-Sdd') option=install ; PACOPTS+=("--nodeps"); MAKEPKGOPTS+=("--nodeps");&
        '-Sd')  option=install ; PACOPTS+=("--nodeps"); MAKEPKGOPTS+=("--nodeps");;
        '-Ss') option=search ;;
        '-Ssq'|'-Sqs') option=search ; quiet='1' ;;
        '-Si') option=info ;;
        '-Sy'|'-Syy') option=reposync; pacmanarg="${1/a/}" ;;
        -S*w*) option=downloadonly; pacmanarg="${1/a/}" ;;
        -S*u*) option=update; pacmanarg="${1/a/}" ;;
      esac ;;

    '-G') option=download ;;
    '-h'|'--help') usage ;;
    '--quiet') quiet='1' ;;
    '--force'|'-f') force='1'; PACOPTS+=("--force");;
    '--ignore') ignorearg="$2" ; PACOPTS+=("--ignore" "$2") ; shift ;;
    '--noconfirm') noconfirm='1' PACOPTS+=("--noconfirm");;
    '--noedit') noedit='1' ;;
    '--aur'|'-a') incaur='1' ;;
    '--auronly') incaur='1'; auronly='1' ;;
    '--quickcheck') quickcheck='1' ;;
    '--devel') devel='1' ;;
    '--skipinteg') MAKEPKGOPTS="--skipinteg" ;;
    '--preview') preview='1' ;;
    '--') shift ; packageargs+=("$@") ; break ;;
    -*)
      $PACMAN "$@"
      exit $?
    ;;
    *) packageargs+=("$1") ;;
  esac
  shift
done

# check for new packages
if [[ $quickcheck == 1 ]]; then
  run_quick_check
  exit
fi

# Sanity checks
[[ $option ]] || option="searchinstall"

if [[ $option == downloadonly ]]; then
  runasroot $PACMAN "${PACOPTS[@]}" "$pacmanarg" "${packageargs[@]}"
  exit $?
fi

if [[ $option == reposync ]]; then
  runasroot $PACMAN "${PACOPTS[@]}" "$pacmanarg"
  installhandling "${packageargs[@]}"
  exit $?
fi

[[ $option != "update" && -z $packageargs ]] && err "Must specify a package."

# Install (-S) handling
if [[ $option = install ]]; then
  installhandling "${packageargs[@]}"
  exit $?
fi

# Update (-Su) handling
if [[ $option = update ]]; then
  getignoredpackages
  sourcemakepkgconf
  # Pacman update
  if ! [[ $auronly ]]; then
    runasroot $PACMAN "${PACOPTS[@]}" "$pacmanarg"
  fi

  if [[ $incaur ]]; then
    # Aur update
    echo -e "${COLOR5}:: ${COLOR1}Synchronizing AUR packages...${ENDCOLOR}"
    IFS=$'\n' read -rd '' -a packages < <(pacman -Qm)
    newpackages=()
    checkignores=()
    total="${#packages[@]}"
    grep -q '^ *ILoveCandy' "$pacmanconf" && bartype='candy' || bartype='normal'

    if [[ $devel ]]; then
      for ((i=0; i<$total; i++)); do
        aurbar "$((i+1))" "$total" "$bartype"
        pkg="${packages[i]%% *}"
        if isignored "$pkg"; then
          checkignores+=("${packages[i]}")
          continue
        fi
        pkginfo "$pkg" &
        nap
      done
      wait
      for ((i=0; i<$total; i++)); do
        pkg="${packages[i]%% *}"
        ver="${packages[i]##* }"
        if [[ ! -s "$tmpdir/$pkg.PKGBUILD" ]]; then
          continue
        fi
        if isignored "$pkg"; then
          continue
        fi
        unset _darcstrunk _cvsroot _gitroot _svntrunk _bzrtrunk _hgroot
        . "$tmpdir/$pkg.PKGBUILD"
        if [[ "$(LC_ALL=C vercmp "$pkgver-$pkgrel" "$ver")" -gt 0 ]]; then
          newpackages+=("$pkg")
        elif [[ ${_darcstrunk} || ${_cvsroot} || ${_gitroot} || ${_svntrunk} || ${_bzrtrunk} || ${_hgroot} ]]; then
          newpackages+=("$pkg")
        elif [[ "$pkg" == *-darcs || "$pkg" == *-cvs || "$pkg" == *-git || "$pkg" == *-svn || "$pkg" == *-bzr || "$pkg" == *-hg ]]; then
          newpackages+=("$pkg")
        fi
      done
    else
      for ((i=0; i<$total; i++)); do
        aurbar "$((i+1))" "$total" "$bartype"
        pkg="${packages[i]%% *}"
        rpcinfo "$pkg" &
        nap
      done
      wait
      for ((i=0; i<$total; i++)); do
        pkg="${packages[i]%% *}"
        ver="${packages[i]##* }"
        if isignored "$pkg"; then
          checkignores+=("${packages[i]}")
        elif aurversionisnewer "$pkg" "$ver"; then
          newpackages+=("$pkg")
      fi
      done
    fi
    echo

    echo -e "${COLOR5}:: ${COLOR1}Starting full AUR upgrade...${ENDCOLOR}"

    # Now for the installation part
    if [[ $newpackages ]]; then
      auronly='1'
      installhandling "${newpackages[@]}"
      exit $?
    fi
    echo " local database is up to date"
  fi

  installhandling "${packageargs[@]}"
fi

# Download (-G) handling
if [[ $option = download ]]; then
  for package in "${packageargs[@]}"; do
    if existsinaur "$package"; then
      pkglist+=("$package")
    else
      err "Package \`$package' does not exist on aur."
    fi
  done

  for package in "${pkglist[@]}"; do
    curl -Lfs "$(pkglink $package)" > "$package.tar.gz"
    mkdir "$package"
    tar xf "$package.tar.gz" -C "$package" --strip-components=1
  done
fi

# Search (-Ss) handling
if [[ $option = search || $option = searchinstall ]]; then
  # Pacman searching
  if ! [[ $auronly ]]; then
    if [[ $quiet ]]; then
      results="$($PACMAN -Ssq -- "${packageargs[@]}")"
    else
      results="$($PACMAN -Ss -- "${packageargs[@]}")"
      results="$(sed -r "s|^[^ ][^/]*/|$S${COLOR3}&$S${COLOR1}|" <<< "$results")"
      results="$(sed -r "s|^([^ ]+) ([^ ]+)(\s?\(.*\))?(\s?\[.*])?$|\1 $S${COLOR2}\2$S${COLOR5}\3$S${COLOR4}\4$S${ENDCOLOR}|" <<< "$results")"
    fi
    if [[ $option = search ]]; then
      echo -e "$results" | fmt -"$_WIDTH" -s -p ' '
    elif [[ $interactive ]]; then  # interactive
      echo -e "$results" | fmt -"$_WIDTH" -s -p ' ' | nl -v 0 -w 1 -s ' ' -b 'p^[^ ]'
    fi | sed '/^$/d'
    pacname=( $($PACMAN -Ssq -- "${packageargs[@]}") )
    pactotal="${#pacname[@]}"
  else
    pactotal=0
  fi

  if [[ $incaur ]]; then
    # Aur searching and tmpfile preparation
    for package in "${packageargs[@]}"; do
      curl -LfGs --data-urlencode "arg=$package" "${RPCURL}=search" | \
      jshon -Q -e results -a -e Name -u -p -e Version -u -p -e NumVotes -u -p -e Popularity -u -p -e OutOfDate -u -p -e Description -u | \
      sed 's/^$/-/' |  paste -s -d "\t\t\t\t\t\n" | sort -k 1 > "$tmpdir/$package.search" &
    done
    wait
    cp "$tmpdir/${packageargs[0]}.search" "$tmpdir/search.results"
    for ((i=1 ; i<${#packageargs[@]} ; i++)); do
      grep -xFf "$tmpdir/search.results" "$tmpdir/${packageargs[$i]}.search" > "$tmpdir/search.results-2"
      mv "$tmpdir/search.results-2" "$tmpdir/search.results"
    done
    sed -i '/^$/d' "$tmpdir/search.results"

    # Prepare tmp file and arrays
    IFS=$'\n' read -rd '' -a aurname < <(cut -f 1 "$tmpdir/search.results")
    aurtotal="${#aurname[@]}"
  else
    aurtotal=0;
  fi

  alltotal="$(($pactotal+$aurtotal))"
  # Echo out the -Ss formatted package information

  IFS=$'\t\n'
  if [[ $option = search ]]; then
    if [[ $quiet ]]; then
      printf "%s\n" ${aurname[@]}
    elif [[ -s "$tmpdir/search.results" ]]; then
      while read LINE; do
        installed=$(installedline "$LINE")
        outofdate=$(outofdateline "$LINE")
        LC_NUMERIC=C printf "${COLOR3}aur/${COLOR1}%s ${COLOR2}%s${ENDCOLOR} ${COLOR6}(%s)${ENDCOLOR} ${COLOR8}(%0.2f)${ENDCOLOR}%c\b \b${installed}${outofdate}\n    %s\n" $LINE
      done < "$tmpdir/search.results"
    fi
  elif [[ $interactive ]]; then
    # interactive
    if [[ $quiet ]]; then
      nl -v ${pactotal:-0} -w 1 -s ' ' <(cut -f 1 "$tmpdir/search.results")
    elif [[ -s "$tmpdir/search.results" ]]; then
      count=${pactotal:-0}
      while read LINE; do
        installed=$(installedline "$LINE")
        outofdate=$(outofdateline "$LINE")
        LC_NUMERIC=C printf "$count ${COLOR3}aur/${COLOR1}%s ${COLOR2}%s${ENDCOLOR} ${COLOR6}(%s)${ENDCOLOR} ${COLOR8}(%0.2f)${ENDCOLOR}%c\b \b${installed}${outofdate}\n    %s\n" $LINE
        let count++
      done < "$tmpdir/search.results"
    fi
  fi | fmt -"$_WIDTH" -s -p ' '
  unset IFS

  # Prompt and install selected numbers
  if [[ $option = searchinstall ]]; then
    pkglist=()
    allpackages=( "${pacname[@]}" "${aurname[@]}" )

    # Exit if there are no matches
    [[ $allpackages ]] || exit

    # Prompt for numbers
    echo
    echo -ne "${COLOR1}Install: ${ENDCOLOR}"
    read -r

    # Parse answer
    if [[ $REPLY ]]; then
      for num in $REPLY; do
        if [[ $num -lt $alltotal ]]; then
          pkglist+=("${allpackages[$num]}")
        fi
      done
    fi

    # Call installhandling to take care of the packages chosen
    installhandling "${pkglist[@]}"
  fi

  # Remove the tmpfiles
  rm -f "$tmpdir/*search" &>/dev/null
  rm -f "$tmpdir/search.result" &>/dev/null
  exit
fi

# Info (-Si) handling
if [[ $option = info ]]; then
  # Pacman info check
  sourcemakepkgconf
  for package in "${packageargs[@]}"; do
    if ! [[ $auronly ]] && existsinpacman "$package"; then
      results="$($PACMAN -Si -- "$package")"
      results="$(sed -r "s|^(Repository[^:]*:)(.*)$|\1$S${COLOR3}\2$S${ENDCOLOR}|" <<< "$results")"
      results="$(sed -r "s|^(Name[^:]*:)(.*)$|\1$S${COLOR1}\2$S${ENDCOLOR}|" <<< "$results")"
      results="$(sed -r "s|^(Version[^:]*:)(.*)$|\1$S${COLOR2}\2$S${ENDCOLOR}|" <<< "$results")"
      results="$(sed -r "s|^(URL[^:]*:)(.*)$|\1$S${COLOR4}\2$S${ENDCOLOR}|" <<< "$results")"
      results="$(sed -r "s|^[^ ][^:]*:|$S${COLOR1}&$S${ENDCOLOR}|" <<< "$results")"
      echo -e "$results\n"
      exit
    elif [[ $incaur ]]; then # Check to see if it is in the aur
      pkginfo "$package" "$preview"
      [[ -s "$tmpdir/$package.PKGBUILD" ]] || err "${COLOR7}error:${ENDCOLOR} package '$package' was not found"
      . "$tmpdir/$package.PKGBUILD"

      # Echo out the -Si formatted package information
      # Retrieve each element in order and echo them immediately
      echo -e "${COLOR1}Repository     : ${COLOR3}aur"
      echo -e "${COLOR1}Name           : $pkgname"
      echo -e "${COLOR1}Version        : ${COLOR2}$pkgver-$pkgrel"
      echo -e "${COLOR1}Description    : ${ENDCOLOR}$pkgdesc"
      echo -e "${COLOR1}Architecture   : ${ENDCOLOR}${arch[@]}"
      echo -e "${COLOR1}URL            : ${COLOR4}$url"
      echo -e "${COLOR1}Licenses       : ${ENDCOLOR}${license[@]}"
      echo -e "${COLOR1}Groups         : ${ENDCOLOR}${groups[@]:-None}"
      echo -e "${COLOR1}Provides       : ${ENDCOLOR}${provides[@]:-None}"
      echo -e "${COLOR1}Depends On     : ${ENDCOLOR}${depends[@]}"
      echo -e "${COLOR1}Make Depends   : ${ENDCOLOR}${makedepends[@]}"
      echo -e -n "${COLOR1}Optional Deps  : ${ENDCOLOR}"

      len="${#optdepends[@]}"
      if [[ $len -eq 0 ]]; then
        echo "None"
      else
        for ((i=0 ; i<$len ; i++)); do
          if [[ $i = 0 ]]; then
            echo "${optdepends[$i]}"
          else
            echo -e "                 ${optdepends[$i]}"
          fi
        done
      fi

      echo -e "${COLOR1}Conflicts With : ${ENDCOLOR}${conflicts[@]:-None}"
      echo -e "${COLOR1}Replaces       : ${ENDCOLOR}${replaces[@]:-None}"
      echo
    fi
  done
fi
