#!/usr/bin/sh

#-------------------
# Usage info
#-------------------
show_help() {
    cat << EOF
Usage: ${0##*/} [-hl] [-t "title"] [-c "caption"] INFILE OUTFILE
Add caption, title and logo to an image, for including in the catalog. 
OPTIONS:  
    -h               Display this help and exit
    -t "title"       Add a title on top of the image
    -c "caption"     Add a caption below the image
    -l               Add the bsc logo to the bottom right of the image
EOF
}

#-------------------
# Initialize flags
#-------------------

titsize=25          # size of the title. It is automatically rescaled if the size of the figure increases/decreases; i.e: if the figure double, the title size doubles too.
captionsize=12      # size of the caption. It is automatically rescaled too.
resizelogo=25       # width of the logo compared to the width of the image (in %). 25% is a good balance. 

cut_title=true     # you can also cut an horizontal strip at the top of the image, if you want to remove and old title before adding the new one with option -t 
cut_title_pixels=50 # set the height of the horizontal strip (in pixels) to remove, if cut_title=false.

OPTIND=1
LOGO=false
LOGO_file=/home/Earth/ncortesi/logo1.png

#-------------------
# Parse input options
#-------------------
while getopts ":t:c:lh" opt; do
  case $opt in
    h)
      show_help
      exit 0
      ;;
    t)
      echo "-t was triggered, Title: $OPTARG" >&2
      TITLE=$OPTARG
      ;;
    c)
      echo "-c was triggered, Caption: $OPTARG" >&2
      CAPTION=$OPTARG
      ;;
    l)
      echo "-l was triggered, Include BSC logo" >&2
      LOGO=true
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done
shift "$((OPTIND-1))" # Shift off the options

#-------------------
# Check we have two args remaining
#-------------------
if [[ $# -ne 2 ]]; 
then
  show_help
  exit 0
fi

#-------------------
# Get in and out files
#-------------------
INFILE=$1
OUTFILE=$2

#-------------------
# Check infile exists
#-------------------
if [[ ! -f $INFILE ]]
then 
  echo "File not found: $INFILE" >&2
  exit -1
fi

####################
# Start doing some work
####################

#------------------------------
# Convert ps to png with 300dpi
#------------------------------
if [[ $INFILE == *.ps ]]
then 
  convert -units PixelsPerInch -density 300 -background white -flatten $INFILE crop.png
else
  cp $INFILE crop.png
fi

# get the width of the image in pixels:
width_figure=$(identify -ping -format %w crop.png)

# get the height of the image in pixels:
height_figure=$(identify -ping -format %h crop.png)

#-------------------
# Add caption
#-------------------
if [[ -v CAPTION ]]
then

    #-------------------------------------
    # In case the logo has to be drawn too
    #-------------------------------------
    if ( $LOGO )
    then
	width_logo_area=$(( $width_figure * $resizelogo / 100 ))
	width_caption_area=$(( $width_figure - $width_logo_area   ))

	width_caption=$(( $width_caption_area * 90 / 100))
	width_logo=$(( $width_logo_area * 90 / 100 ))
	width_logo_file=$(identify -ping -format %w $LOGO_file)

	# 1) create the caption:
	captionsize_rescaled=$(( $captionsize * $width_figure / 600))
	convert -background white -font Arial -pointsize $captionsize_rescaled -size ${width_caption}x -define pango:justify=true pango:"$CAPTION" -geometry +0+0 crop1.png

	# 2) insert the caption at the top center of the caption area:
	convert crop1.png -gravity North -background white -extent ${width_caption_area}x crop2.png

	# 3) resize the logo, to be proportional to the size of the figure:
	resize_logo=$(( $width_logo * 100 / $width_logo_file ))
	convert -background white $LOGO_file -scale ${resize_logo}% crop3.png

	# 4) insert the logo over a larger canvas, (the logo area), in its top left part:
	height_caption_area=$(identify -ping -format %h crop2.png)
	height_logo_resized=$(identify -ping -format %h crop3.png)

	if [[ $height_caption_area -lt $height_logo_resized ]]; then
	    height_logo_area=$height_logo_resized
	else
	    height_logo_area=$(identify -ping -format %h crop1.png)
	fi

	convert crop3.png -gravity NorthWest -background white -extent ${width_logo_area}x${height_logo_area} crop4.png

	# if the caption is less high than the logo, insert the caption at the center of the caption area instead than at the top center:
	if [[ $height_caption_area -lt $height_logo_resized ]]; then
	    convert crop1.png -gravity Center -background white -extent ${width_caption_area}x${height_logo_area} crop2.png
	fi

	# 5) Merge the caption area and the logo area together:
	montage crop2.png crop4.png -tile 2x1 -geometry +0+0 crop5.png

	# 6) Add a white horizontal strip over the caption+logo area:
	convert -size x20 xc:white crop6.png
	montage crop6.png crop5.png -tile 1x2 -geometry +0+0 crop7.png

	# 7) Add a white horizontal strip below the caption+logo area:
	if [[ $height_caption_area -ge $height_logo_resized ]]; then
	    convert -size x20 xc:white crop8.png
	    montage crop7.png crop8.png -tile 1x2 -geometry +0+0 crop9.png
	else
	    convert -size x5 xc:white crop8.png
	    montage crop7.png crop8.png -tile 1x2 -geometry +0+0 crop9.png 
	fi

	# 8) Add the figure:
	montage crop.png crop9.png -tile 1x2 -geometry +0+0 crop10.png

    else  
	#-------------------------
	# In case there is no logo
	#-------------------------

        width_caption=$(( $width_figure * 90 / 100))
        
	# 1) Create the caption:
	captionsize_rescaled=$(( $captionsize * $width_figure / 600))
	convert -background white -font Arial -pointsize $captionsize_rescaled -size ${width_caption}x -define pango:justify=true pango:"$CAPTION" -geometry +0+0 crop1.png

	# 2) Insert the caption at the top center of the caption area:
	convert crop1.png -gravity North -background white -extent ${width_figure}x crop2.png

	# 3) Add a white horizontal strip over the caption area:
	convert -size x20 xc:white crop3.png
	montage crop3.png crop2.png -tile 1x2 -geometry +0+0 crop7.png

	# 4) Add a white horizontal strip below the caption area:
	convert -size x20 xc:white crop8.png
	montage crop7.png crop8.png -tile 1x2 -geometry +0+0 crop9.png

	# 5) Add the figure:
	montage crop.png crop9.png -tile 1x2 -geometry +0+0 crop10.png

        # xdg-open crop10.png # for the debug

    fi # end if on LOGO
else
    #----------------------------
    # In case there is no caption
    #----------------------------

    CAPTION=""

    if ( $LOGO )
    then
        #-------------------------------------
        # In case the logo has to be drawn too
        #-------------------------------------

   	width_logo_area=$(( $width_figure * $resizelogo / 100 ))
	width_caption_area=$(( $width_figure - $width_logo_area   ))

	width_caption=$(( $width_caption_area * 90 / 100))
	width_logo=$(( $width_logo_area * 90 / 100 ))
	width_logo_file=$(identify -ping -format %w $LOGO_file)

	# 1) create the caption:
	captionsize_rescaled=$(( $captionsize * $width_figure / 600))
	convert -background white -font Arial -pointsize $captionsize_rescaled -size ${width_caption}x -define pango:justify=true pango:"$CAPTION" -geometry +0+0 crop1.png

	# 2) insert the caption at the top center of the caption area:
	convert crop1.png -gravity North -background white -extent ${width_caption_area}x crop2.png

	# 3) resize the logo, to be proportional to the size of the figure:
	resize_logo=$(( $width_logo * 100 / $width_logo_file ))
	convert -background white $LOGO_file -scale ${resize_logo}% crop3.png

	# 4) insert the logo over a larger canvas, (the logo area), in its top left part:
	height_caption_area=$(identify -ping -format %h crop2.png)
	height_logo_resized=$(identify -ping -format %h crop3.png)

	if [[ $height_caption_area -lt $height_logo_resized ]]; then
	    height_logo_area=$height_logo_resized
	else
	    height_logo_area=$(identify -ping -format %h crop1.png)
	fi

	convert crop3.png -gravity NorthWest -background white -extent ${width_logo_area}x${height_logo_area} crop4.png

	# if the caption is less high than the logo, insert the caption at the center of the caption area instead than at the top center:
	if [[ $height_caption_area -lt $height_logo_resized ]]; then
	    convert crop1.png -gravity Center -background white -extent ${width_caption_area}x${height_logo_area} crop2.png
	fi

	# 5) Merge the caption area and the logo area together:
	montage crop2.png crop4.png -tile 2x1 -geometry +0+0 crop5.png

	# 6) Add a white horizontal strip over the caption+logo area:
	convert -size x20 xc:white crop6.png
	montage crop6.png crop5.png -tile 1x2 -geometry +0+0 crop7.png

	# 7) Add a white horizontal strip below the caption+logo area:
	if [[ $height_caption_area -ge $height_logo_resized ]]; then
	    convert -size x20 xc:white crop8.png
	    montage crop7.png crop8.png -tile 1x2 -geometry +0+0 crop9.png
	else
	    convert -size x5 xc:white crop8.png
	    montage crop7.png crop8.png -tile 1x2 -geometry +0+0 crop9.png 
	fi

	# 8) Add the figure:
	montage crop.png crop9.png -tile 1x2 -geometry +0+0 crop10.png

    else
        #---------------------------------------------------------
        # In case there is only the title, and caption and no logo
        #---------------------------------------------------------
        cp crop.png crop10.png

    fi  # end if on LOGO

fi  # end if on CAPTION


#------------------------------------------
# Cut old title
#------------------------------------------

if ( $cut_title ); then
    # cut the upper part of the image of the desired size to remove the old title:
    convert crop10.png -crop +0+${cut_title_pixels} +repage crop10.png
fi

#------------------------------------------
# Add title
#------------------------------------------

if [[ -v TITLE ]]
then 
    # add the new title:
    titsize_rescaled=$(( $titsize * $width_figure / 600))
    convert crop10.png -background white -pointsize $titsize_rescaled label:"$TITLE" +swap -gravity Center -append crop11.png    
    cp crop11.png crop10.png
fi


cp crop10.png $OUTFILE

# remove all temporary files:
rm crop*.*
