#!/usr/bin/bash

# get version from base hplip rpm - it is always in the second column
VER=$(/usr/bin/rpm -q hplip | /usr/bin/awk -F '-' '{print $2}')

if test "x$VER" = "x"
then
  /usr/bin/echo "Version was not acquired - exiting..."
  exit 1
fi

# plugin name
PLUGIN_FILE="hplip-${VER}-plugin.run"

download()
{
  SOURCE="$1"

  /usr/bin/curl --create-dirs -O  --output-dir ~/.hplip --location ${SOURCE}
}

# link to the plugin
PLUGIN_SOURCE="https://www.openprinting.org/download/printdriver/auxfiles/HP/plugins/${PLUGIN_FILE}"
FALLBACK_SOURCE="https://developers.hp.com/sites/default/files/${PLUGIN_FILE}"

# create a hidden hplip dir to store a file indicating the plugin version after successful install
# the directory can be used by other hplip tools, so we don't have to remove it if the failure happens
if [ ! -d ~/.hplip ]
then
  /usr/bin/mkdir ~/.hplip || (/usr/bin/echo "Cannot create the ~/.hplip dir, exiting" && exit 1)
fi

for link in ${PLUGIN_SOURCE} ${FALLBACK_SOURCE}
do
  download ${link}

  if test "x$(file --mime ~/.hplip/${PLUGIN_FILE} | grep -o 'text/x-shellscript')" = "xtext/x-shellscript"
  then
    break
  fi
done

if test "x$(file --mime ~/.hplip/${PLUGIN_FILE} | grep -o 'text/x-shellscript')" = "x"
then
  /usr/bin/echo "The downloaded file does not exist or is not a shell script - error during downloading, exiting..."
  exit 1
fi

/usr/bin/bash ~/.hplip/${PLUGIN_FILE}

if [ $? -ne 0 ]
then
  /usr/bin/echo "Plugin installation failed, exiting..."
  /usr/bin/rm -f ~/.hplip/${PLUGIN_FILE} &> /dev/null
  exit 1
fi

/usr/bin/rm -f ~/.hplip/${PLUGIN_FILE} &> /dev/null
/usr/bin/rm -f ~/.hplip/plugin-installed-* &> /dev/null
/usr/bin/touch ~/.hplip/plugin-installed-$VER

exit 0
