#!/usr/bin/env bash
######################################################################
#Copyright (C) 2025 Kris Occhipinti
#http://filmsbykris.com

#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation version 3 of the License.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
######################################################################

# Create a qrcode with an image in the center
while getopts i:t:o:hq flag; do
  case "${flag}" in
  i) image=${OPTARG} ;;
  t) text=${OPTARG} ;;
  o) output=${OPTARG} ;;
  q) quiet=${OPTARG} ;;
  h) help="true" ;;
  esac
done

# fatal uses SIGUSR1 to allow clean fatal errors
trap "exit 1" 10
PROC=$$

function error() {
  red=$(echo -en "\e[31m")
  normal=$(echo -en "\e[0m")

  echo -e "${red}$@${normal}" >&2
  # print help if quiet not set
  [[ $quiet ]] && help
  #  exit 1
  kill -10 $PROC
}

function help() {
  local name="$(basename $0)"
  echo "
  Usage: $name -t <text for qr> -i <image for center> -o <output image>
  Example: $name -t "https://filmsbykris.com" -i "image_01.png" -o "myqr.png"
  "
  exit
}

function qr_check() {
  # check new qr and make sure it matches input
  msg="$(zbarimg -q --raw "$output")"
  [[ "$msg" == "$text" ]] && return

  # Extract the directory name
  dir_name="$(dirname "$output")"

  # Extract the file name
  file_name="$(basename "$output")"
  [[ $dir_name ]] && new_output="${dir_name}/error_${file_name}" || new_output="error_${file_name}"
  mv "$output" "$new_output"
  error "The output of $new_output does not match the image text given"
}

[[ $help ]] && help && exit

[[ $text ]] || read -p "Text for QR: " text
[[ $text ]] || exit

[[ $image ]] || read -p "Image file for center of QR: " image
[[ -f "$image" ]] || error "$image does not exist"

# if not output give create one useing time stamp
[[ $output ]] || output="qr_$(date +%s).png"
[[ "$output" == *.png ]] || output="$output.png"
qrencode "$text" -o "$output" -s 20 -v15

# get width of qr image in pixels
qrsize="$(identify -format "%w" "$output")"
imagesize=$(($qrsize / 4))
# echo "$output is $qrsize pixels wide"
# echo "Resize $image to $imagesize"
# Overlay image on qr at 1/4 the size of qr on the longest size
convert "$output" \( "$image" -resize ${imagesize}x${imagesize}\> -gravity center \) -composite "$output"

qr_check
echo "$output has been created with the text of $msg"
