#!/bin/bash

## This script is a workaround for installing shellcheck with the precompiled
# binary. It is intended to be run when the shellcheck package isn't found via
# pacman.

RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
ORANGE=$(tput setaf 3)
NC=$(tput sgr0)

if ! sudo pacman -S --needed shellcheck; then
  echo "  ${ORANGE}Shellcheck was not found with pacman, downloading pre-compiled binary${NC}"
  scversion="stable"
  architechture=$(uname -m)
  if [ -e ~/Downloads/shellcheck-${scversion} ]; then
    rm -r ~/Downloads/shellcheck-${scversion} && echo "  ${ORANGE}Found and removed pre-existing shellcheck folder${NC}"
  fi
  cd ~/Downloads || exit 1
  echo "  Downloading shellcheck ${scversion} binary for ${architechture}..."
  if wget -qO- "https://storage.googleapis.com/shellcheck/shellcheck-${scversion?}.linux.${architechture?}.tar.xz" | tar -xJv; then
    echo "  ${GREEN}Successfully downloaded and extracted shellcheck.${NC}"
    echo "  Copying executable to /usr/bin/ ..."
    sudo cp "shellcheck-${scversion}/shellcheck" /usr/bin/ && shellcheck --version
    if rm -r ~/Downloads/shellcheck-${scversion}; then
      echo "  ${GREEN}Removed shellcheck installation folder${NC}"
    else
      echo "  ${RED}Was unable to remove shellcheck installation folder${NC}"
      exit 1
    fi
  else
    echo "  ${RED}Was unable to download shellcheck binary${NC}"
  fi
fi