#!/usr/bin/bash

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

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

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

download()
{
  SOURCE="$1"

  @bindir@/curl --create-dirs -O  --output-dir ~/.hplip ${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
  @bindir@/mkdir ~/.hplip || (@bindir@/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 'text/x-shellscript')" = "xtext/x-shellscript"
  then
    break
  fi
done

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

@bindir@/bash ~/.hplip/${PLUGIN_FILE}

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

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

exit 0