#!/bin/sh
# install AUR packages
basebuilddir="$HOME/.simpleaur/Build"
pkgdown="$HOME/.simpleaur/pkgbuilds"
lockfile="$basebuilddir/simpleaur.lock"

# prefer terminal safe colored and bold text when tput is supported - /usr/share/makepkg/util/message.sh
if tput setaf 0 &>/dev/null; then
  ALL_OFF="$(tput sgr0)"
  BOLD="$(tput bold)"
  BLUE="${BOLD}$(tput setaf 4)"
  GREEN="${BOLD}$(tput setaf 2)"
  RED="${BOLD}$(tput setaf 1)"
  YELLOW="${BOLD}$(tput setaf 3)"
else
  ALL_OFF="\e[0m"
  BOLD="\e[1m"
  BLUE="${BOLD}\e[34m"
  GREEN="${BOLD}\e[32m"
  RED="${BOLD}\e[31m"
  YELLOW="${BOLD}\e[33m"
fi
readonly ALL_OFF BOLD BLUE GREEN RED YELLOW

function lockfilecheck() {
  #Prevent two instances running at same time
  if [ -f "$lockfile" ]; then
    printf "\n${RED}simpleaur is running, leaving.\n"
    printf "\n${RED}If you are sure that simpleaur is not running, delete [ $lockfile ]\n"
    exit
  else
    touch "$lockfile"
  fi
}

function usage(){
  printf "${RED}Usage:
  simpleaur package1 package2        Install package1 and package2 from AUR.
  --help, -h                         Show it dialog.
  --purge, -p                        Delete all compiled packages in $basebuilddir.
  --download, -d                     Download all PKGBUILDS of packages passed as arguments in $pkgdown.
  --purgepkg, -pp                    Delete all downloaded PKGBUILDS in $pkgdown.
  --search, -s                       Search for packages in AUR.
  --rebuild-git, -rg                 Rebuild all CVS AUR packages.
  --check, -c                        Check available updates for packages installed from AUR.\n${ALL_OFF}"
}

function ctrl_c() {
  printf "\n${RED}Keyboard Interrupt detected, removing lock file and leaving...\n"
  rm "$lockfile"
  printf "${ALL_OFF}"
  exit
}

trap ctrl_c 2

#Check if the base Build DIR exists, if not create it.
if [ ! -d "$basebuilddir" ]; then
  mkdir -p "$basebuilddir"
elif [ ! -d "$pkgdown" ]; then
  mkdir -p "$pkgdown"
fi

#Check for arguments passed to simpleaur
if [ "$1" == "--help" ] || [ "$1" == "-h" ] || [ -z "$*" ]; then
  usage
  exit
elif [ "$1" == "--purge" ] || [ "$1" == "-p" ]; then
  rm -rf "$basebuilddir"/*
  exit
elif [ "$1" == "--purgepkg" ] || [ "$1" == "-pp" ]; then
  rm -rf "$pkgdown"/*
  exit

# The next 11 lines allow users to download PKGBUILDs from AUR
elif [ "$1" == "--download" ] || [ "$1" == "-d" ]; then
  for pkgname in "${@:2}"; do
    curl -s -f -o "$pkgdown/PKGBUILD-$pkgname" "https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=$pkgname"
    if [ "$?" -eq 0 ]; then
      printf "\n${GREEN}Your PKGBUILD for [ $pkgname ] was saved in: ${YELLOW}[ $pkgdown/PKGBUILD-$pkgname ].${ALL_OFF}\n"
    else
      printf "\n${RED}Error: Failed to download the PKGBUILD for ${YELLOW}[ $pkgname ], ${RED}check the package name, your internet connection and try again.${ALL_OFF}\n"
    fi
  done
  printf "\n${GREEN}All done, leaving.${ALL_OFF}\n"
  exit

# The following lines add support for search packages only if auracle is installed https://aur.archlinux.org/packages/auracle-git
elif [ "$1" == "--search" ] || [ "$1" == "-s" ]; then
  if command -v auracle > /dev/null; then
      auracle search "${@:2}"
  else
    printf "${RED}You need to install auracle ${YELLOW}(https://aur.archlinux.org/packages/auracle-git)${RED} to use it option. You can install it running in your terminal: simpleaur auracle-git or installing it manually.\n${ALL_OFF}"
  fi
  exit

# Lines for check package updates from AUR only if auracle is installed https://aur.archlinux.org/packages/auracle-git
elif [ "$1" == "--check" ] || [ "$1" == "-c" ]; then
  if command -v auracle > /dev/null; then
    printf '\e[1;32m%-6s\e[m\n' 'The following packages are availables for update, you can update them using: simpleaur package1 package2 package3'
    auracle sync
  else
    printf "${RED}You need to install auracle ${YELLOW}(https://aur.archlinux.org/packages/auracle-git)${RED} to use it option. You can install it running in your terminal: simpleaur auracle-git or installing it manually.\n${ALL_OFF}"
  fi
  exit
elif [ "$1" == "-rg" ] || [ "$1" == "--rebuild-git" ]; then
  packages=$(pacman -Qqm |grep git)
  "$0" $packages
  exit
else
  cd "$basebuilddir" || exit
fi

#Make sure that you are using an ArchLinux system
if ! command -v pacman > /dev/null; then
  printf "\n${RED}Error: You are not using ArchLinux, pacman was not found in ($PATH)\n"
  exit
fi

logfilecheck
# Check if the package was already downloaded and then download the PKGBUILDs accordly to user needs.
for ipackage in "$@"; do
  if [ -f "$basebuilddir/$ipackage/PKGBUILD" ]; then
    printf "\n${GREEN}PKGBUILD for ${BLUE}[ $ipackage ] ${GREEN}exist in the ${BLUE}[ $basebuilddir/$ipackage ] ${GREEN}directory, pulling the git directory and reinstalling/updating the packages.${ALL_OFF}\n"
    cd "$basebuilddir/$ipackage" || exit
    git pull
    cd "$basebuilddir" || exit
    continue
  else
    git clone "https://aur.archlinux.org/${ipackage}.git"
  fi
done

# Check PKGBUILDs.
for ipackage in "$@"; do
  if [ -d "$basebuilddir/$ipackage" ] && [ -s "$basebuilddir/$ipackage/PKGBUILD" ]; then
    cd "$basebuilddir/$ipackage" || exit
    printf "${BLUE}View PKGBUILD for [ $ipackage ] ? [Y/n] ${ALL_OFF}"
    read -r answer
    if [ "$answer" = "y" ] || [ "$answer" = "Y" ]  ; then
      ${EDITOR} PKGBUILD
    fi
  else
    printf "${RED}The package ${YELLOW}[ $ipackage ] ${RED}does not exist in AUR, building the rest of the packages if exist.\n${ALL_OFF}"
    rm -rf "$basebuilddir/$ipackage"
  fi
done

cd "$basebuilddir" || exit

# Install packages.
for ipackage in "$@"; do
  if [ -d "$ipackage" ]; then
    cd "$ipackage" || exit
    if makepkg -sci ; then
      cd "$basebuilddir" || exit
      printf "\n${GREEN}The package ${BLUE}[ $ipackage ] ${GREEN}has been installed.\n"
      continue
    else
      printf "\n${RED}Error: Installation for the package ${BLUE}[ $ipackage ] ${RED}was not completed, building the rest of the packages if exist.\n${ALL_OFF}"
      cd "$basebuilddir" || exit
    fi
  fi
done

printf "\n${GREEN}Info: finishing tasks...
Deleting the simpleaur lockfile...
Good bye${ALL_OFF}\n"
rm -f "$lockfile"
exit
