#!/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

# link to the plugin
PLUGIN_SOURCE="https://www.openprinting.org/download/printdriver/auxfiles/HP/plugins/hplip-${VER}-plugin.run"

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

# 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

/usr/bin/wget -O ~/.hplip/${PLUGIN_FILE} ${PLUGIN_SOURCE}

if [ ! -f ~/.hplip/${PLUGIN_FILE} ]
then
  /usr/bin/echo "The downloaded file does not exist - 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
