#!/bin/bash
#
# OP Cloud Connector v.4.4 installer 
# https://fitosoft.com/webhelp/source/connector.htm
#
# Developed by Fitosoft, Inc.
# Contact info@fitosoft.com
#
# 1. Give the shell permission to execute install script. 
# $ sudo chmod 755 install.sh
# 2. Script will run
# $ ./install.sh
#

echo -e "OP Cloud installer v.4.4"
echo -e "----------------------------\n"

sudo apt-get install python
sudo apt-get install python-pil
sudo apt-get install libcups2-dev 
sudo apt-get install python-cups

# Copy tea4cups.conf into CUPS' configuration directory, usually /etc/cups/
sudo cp -rv ./tea4cups/tea4cups.conf /etc/cups/

# Copy tea4cups into CUPS' backends directory, usually /usr/lib/cups/backend/
sudo cp -rv ./tea4cups/tea4cups /usr/lib/cups/backend/

# For CUPS v1.2 or higher /usr/lib/cups/backend/tea4cups is owned by user root and group root, and executable by user root only (chmod 700)
sudo chown root.root /usr/lib/cups/backend/tea4cups
sudo chmod 700 /usr/lib/cups/backend/tea4cups

# Install pkpgcounter
cd pkpgcounter
sudo python ./setup.py install
cd .. 

# Copy op-desktop-connector.py into CUPS' directory
sudo cp -rv ./op-cloud-connector.py /etc/cups/
sudo chmod 700 /etc/cups/op-cloud-connector.py

sudo sed -i 's/#prehook_accounting : echo $TEAPRINTERNAME $TEAJOBID $TEAUSERNAME $TEABILLING `pkpgcounter $TEADATAFILE` >>\/var\/log\/printaccounting.log/prehook_accounting : python \/etc\/cups\/op-cloud-connector.py --JobId=$TEAJOBID --PrinterName=$TEAPRINTERNAME --MachineName=$TEACLIENTHOST --UserName=$TEAUSERNAME --SpoolerFile=$TEADATAFILE --Size=$TEAJOBSIZE --Copies=$TEACOPIES --Document=$TEATITLE $TEAOPTIONS/g' /etc/cups/tea4cups.conf 

#install ghostpdl
FILE_GS=/usr/local/bin/gs
FILE_XPS=/usr/local/bin/gxps
FILE_PCL=/usr/local/bin/gpcl6

files_exist="yes"

if ! [ -f "$FILE_GS" ]; then
  files_exist="no"
fi

if ! [ -f "$FILE_XPS" ]; then
  files_exist="no"
fi

if ! [ -f "$FILE_PCL" ]; then
  files_exist="no"
fi

if  [ $files_exist = "yes" ]; then
  echo "Skip ghostpdl installation"
else 
  sudo wget https://github.com/ArtifexSoftware/ghostpdl-downloads/releases/download/gs927/ghostpdl-9.27.tar.gz
  sudo tar -zxf ghostpdl-9.27.tar.gz
  cd ghostpdl-9.27
  sudo ./configure
  sudo make all
  cd ..
  sudo cp -rv ./ghostpdl-9.27/bin/gs /usr/local/bin
  sudo cp -rv ./ghostpdl-9.27/bin/gxps /usr/local/bin
  sudo cp -rv ./ghostpdl-9.27/bin/gpcl6 /usr/local/bin
  sudo rm ./ghostpdl-9.27.tar.gz
  sudo rm -rf ghostpdl-9.27
fi

until sudo python ./op-cloud-connector-setup.py; do
  echo Error occured, retrying in 5 seconds...
  sleep 5
done

# Restart CUPS
sudo service cups restart




