#!/usr/bin/bash
# Copyright 2019-2021 Chad Lemmen http://www.lemmen.com
#
################################################################################
# File:     modps
# Date:     2019-11-16
# Author:   Chad Lemmen http://www.stansoft.org
# Purpose:  Modify a postscript file by adding horizontal lines and logo 
# History:
#           2021-12-03 CDL - Added inserting a logo onto an invoice.
#
################################################################################

in=$(cat $1)

# A4 paper is 94 columns at 12cpi
col=94

###########
# Functions
###########

func_add_logo () {
  filecmd="identify"
  source lib.sh
  func_set_sqlcmd

  logofile=$($sqlcmd stansoft <<SQL
    $noheading
    select trim(parm_field) from sys_parm where parm_nbr = 6015;
SQL
  )

  if [ -z "$logofile" ]; then
    # No logo file set... abort adding logo
    return
  fi

  # Command 'identify' from ImageMagick must be installed
  if ! hash "$filecmd" 2>/dev/null; then
    func_log_error "$0" "'$filecmd' could not be found, you must install it."
    return
  fi

  read w h fmt <<<$("$filecmd" -format '%w %h %m' "$logofile")

  if [ "$fmt" != "JPEG" ]; then
    func_log_error "$0" "The image file must be JPEG format."
    return
  fi

  # The max image size to fit on the invoice is 200x40
  if [ "$w" -gt 200 ]; then
    maxw=200
  else
    maxw="$w"
  fi
  if [ "$h" -gt 40 ]; then
    maxh=40
  else
    maxh="$h"
  fi


  in=$(sed "/%%EndPageSetup/a gsave \n\
    215 710 translate             % position lower left of image\n\
    $maxw $maxh scale             % scale image size\n\
    $w $h 8                       % columns by rows by color bit-depth\n\
    [$w 0 0 -$h 0 $h]             % ImageMatrix [width 0 0 -height 0 height]\n\
    ($logofile) (r) file          % open the file\n\
    /DCTDecode filter             % filter the jpg image\n\
    false                         % pull channels from separate sources\n\
    3                             % 3 color channels (RGB)\n\
    colorimage\n\
grestore" <<<"$in")
}

###############
# End Functions
###############


#
# Add logo image
#
if grep -q "Product Description                                       Quantity Unit       Price  Extension" <<<"$in"; then
  # Input is an invoice, add logo to it.
  func_add_logo
fi


#
# Add horizontal lines
#
for sym in = -; do
  # Put the line start coordinates into an array using regex to search
  # for the pattern, {n} exactly n times, {n,} at least n times
  arr=( $(grep -B 1 -E "\([$sym]{$col}\)" <<< "$in" | grep [[:digit:]] | cut -d' ' -f1-2) )

  if [ "$sym" == "-" ]; then
    linewidth=1
    #adjust=3
    # Removing both the symbols only needs to be done once in the loop
    printf "%s\n" "s/[=-]{$col}//"
  else
    linewidth=2
    #adjust=3
  fi

  for ((i=0; i<${#arr[@]}; i+=2)); do # step through index values by 2
    x="${arr[$i]}"
    y="${arr[$i+1]}"
    #y=$(bc <<< "$y + $adjust") # moving up $adjust is needed to cover the line

    # n string stringwidth pop, returns the width of a string repeated n times
    printf "%s\n" "/%%EndPageSetup/a newpath \
                                     $x $y moveto \
                                     95 string stringwidth pop $y lineto \
                                     $linewidth setlinewidth \
                                     stroke"
  done
done | sed -r -f- <(echo "$in") # use process substitution since we cannot
                                # pipe and redirect stdin at the same time

