#!/usr/bin/sh
#-------------------
# Usage info
#-------------------
show_help() {
  cat << EOF
Usage: ${0##*/} [-hl] [-t "title"] [-c "caption"] [-s scale_factor] 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
    -r pixels        Remove an horizontal strip at the top of the image
                     of height equal to the specified number of pixels,
                     in case there is a pre-existing title to delete
    -p pixels        Add a white horizontal strip between the title and the figure
    -c "caption"     Add a caption below the image
    -m pixels        Remove an horizontal strip between the image and the caption,
                     if the distance to the caption is too much
    -x pixels        Add a white horizontal strip between the image and the caption
    -s scale_factor  Rescale font size of both title and caption by this factor
    -l               Do not add the bsc logo
EOF
}

#-------------------
# Initialize flags and settings
#-------------------

captionsize=25		# size of the caption. It is automatically rescaled depending on the image width.	
resizefont=1		# scale factor for both title and fonts

OPTIND=1		# needed for getopts maths
LOGO=true               # flag for logo exclusion
resizelogo=25           # width of the logo compared to the width of the image (in %). 25% is a good balance. 
LOGO_file=/esarchive/scratch/ncortesi/scripts/images/logo.png ## /shared/earth/Operational/EDPR/logo.png

cut_title=false         # cut an horizontal strip at the top of the figure, if you want to remove and old title before adding the new one with option -t 
cut_title_pixels=0	# set the height of the horizontal strip (in pixels) to remove, if cut_title=false
cut_bottom=false        # cut an horizontal strip between the figure and the caption, if there is too much white space at the bottom of the figure
cut_bottom_pixels=0

add_strip_above_title=20   # space above the title in pixel
add_strip_below_title=0    # space between title and original figure in pixel
add_strip_above_caption=0  # space between original figure and caption in pixel
add_strip_below_caption=20 # space below caption in pixel

#-------------------
# Parse input options
#-------------------
while getopts ":t:r:p:c:m:x:s:s:lh" opt; do
  case $opt in
    h)
      show_help
      exit 0
      ;;
    t)
      #echo "-t was triggered, Title: $OPTARG" >&2
      TITLE=$OPTARG
      ;;
    r)
      #echo "-r was triggered, Title: $OPTARG" >&2
      cut_title=true
      cut_title_pixels=$OPTARG
      ;;
    p)
      #echo "-p was triggered, Caption: $OPTARG" >&2
      add_strip_below_title=$OPTARG
      ;;
    c)
      #echo "-c was triggered, Caption: $OPTARG" >&2
      CAPTION=$OPTARG
      ;;
    m)
      #echo "-m was triggered, Title: $OPTARG" >&2
      cut_bottom=true
      cut_bottom_pixels=$OPTARG
      ;;
    x)
      #echo "-p was triggered, Caption: $OPTARG" >&2
      add_strip_above_caption=$OPTARG
      ;;
    l)
      #echo "-l was triggered, Include BSC logo" >&2
      LOGO=false
      ;;
    s)
      #echo "-c was triggered, Caption: $OPTARG" >&2
      resizefont=$OPTARG
      ;;
    \?)
      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
####################
#------------------------------
# Create a tmp folder to store intermediate files.
# It will be cleared by system.
#------------------------------
TMP="$(mktemp -d)"
#echo "Working in "$TMP" folder."
#------------------------------
# Convert ps to png with 300dpi
#------------------------------
if [[ $INFILE == *.ps ]] ; then 
  convert -units PixelsPerInch -density 300 -background white -flatten $INFILE $TMP/figure.png
else
  cp $INFILE $TMP/figure.png
fi
#------------------------------
# Get the width and height of the image and logo, in pixels.
#------------------------------
width_figure=$(identify -ping -format %w $TMP/figure.png)
height_figure=$(identify -ping -format %h $TMP/figure.png)
width_logo_file=$(identify -ping -format %w $LOGO_file)
#------------------------------
# Set the width of logo and logo area.
#------------------------------
width_logo_area=$(( $width_figure * $resizelogo / 100 ))
width_logo=$(( $width_logo_area * 90 / 100 ))
resize_logo=$(( $width_logo * 100 / $width_logo_file ))
#------------------------------
# Set the width of caption and caption area.
#------------------------------
if ( $LOGO ) ; then
  width_caption_area=$(( $width_figure - $width_logo_area   ))
else
  width_caption_area=$width_figure
fi
width_caption=$(( $width_caption_area * 90 / 100))

#------------------------------
# Set rescaled sizes for fonts and other tricks
#------------------------------
resizefont=$( echo "scale=3; $width_figure*$resizefont/125" | bc )

if [[ $width_figure -gt 1000 ]]; then
  captionsize=$(( $captionsize - 2 ))
  if [[ $width_figure -gt 1500 ]]; then
    captionsize=$(( $captionsize - 3 ))
    if [[ $width_figure -gt 2000 ]]; then
       captionsize=$(( $captionsize - 2 ))
       if [[ $width_figure -gt 3000 ]]; then
          captionsize=$(( $captionsize - 3 ))
       fi
    fi
  fi
fi

captionsize_rescaled=$( echo "$captionsize*$resizefont/10" | bc )
titsize_rescaled=$( echo "scale=3; $captionsize_rescaled*150/100" | bc ) # 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.

#------------------
# We need to create a footer?
# (either caption or logo or both)
#------------------
if [[ -v CAPTION ]] || ( $LOGO ) ; then
  #---------------------
  # Create the caption and insert it at the top center of the caption area.
  # NOTE: if caption is unset it writes an empty string anyway.
  #---------------------
  convert -background white -font Arial -pointsize $captionsize_rescaled -size ${width_caption}x -define pango:justify=true pango:"$CAPTION" -geometry +0+0 $TMP/caption.png
  convert $TMP/caption.png -gravity North -background white -extent ${width_caption_area}x $TMP/caption_area.png
  height_caption=$(identify -ping -format %h $TMP/caption.png)
  height_caption_area=$(identify -ping -format %h $TMP/caption_area.png)
  #--------------------------
  # Draw the logo if needed
  #--------------------------
  if ( $LOGO ) ; then
    #---------------------
    # Resize the logo, to be proportional to the size of the figure
    #---------------------
    convert -background white $LOGO_file -scale ${resize_logo}% $TMP/logo.png
    height_logo_resized=$(identify -ping -format %h $TMP/logo.png)
    #---------------------
    # Set height of logo area.
    # If the caption is less high than the logo, insert the caption at the center of
    # the caption area rather than at the top center (This overwrites previous image).
    # In this case also set fewer space below footer
    #---------------------
    if [[ $height_caption_area -lt $height_logo_resized ]]; then
      height_logo_area=$height_logo_resized
      convert $TMP/caption.png -gravity Center -background white -extent ${width_caption_area}x${height_logo_area} $TMP/caption_area.png
      size_space=5
    else
      height_logo_area=$height_caption
    fi
    #---------------------
    # Insert the logo at top left of the logo area
    #---------------------
    convert $TMP/logo.png -gravity NorthWest -background white -extent ${width_logo_area}x${height_logo_area} $TMP/logo_area.png
    #---------------------
    # Merge the caption area and the logo area together
    #---------------------
    montage $TMP/caption_area.png $TMP/logo_area.png -tile 2x1 -geometry +0+0 $TMP/footer.png
  else
    #--------------------------
    # No logo: set the caption area as footer
    #--------------------------
    mv $TMP/caption_area.png $TMP/footer.png
  fi
  #--------------------------
  # Optional: remove the bottom part of the figure
  #--------------------------
  if ( $cut_bottom ); then
    convert $TMP/figure.png -crop +0-${cut_bottom_pixels} +repage $TMP/figure.png
  fi
  #---------------------
  # Add a white horizontal strip above the footer area
  #---------------------
  convert -size x${add_strip_above_caption} xc:white $TMP/space.png
  montage $TMP/space.png $TMP/footer.png -tile 1x2 -geometry +0+0 $TMP/footer.png
  #---------------------
  # Add a white horizontal strip below the footer area
  #---------------------
  convert -size x${add_strip_below_caption} xc:white $TMP/space.png
  montage $TMP/footer.png $TMP/space.png -tile 1x2 -geometry +0+0 $TMP/footer.png
  #---------------------
  # Add the footer to the figure
  #---------------------
  montage $TMP/figure.png $TMP/footer.png -tile 1x2 -geometry +0+0 $TMP/fig_and_footer.png
else
  #---------------------
  # No title and no logo
  #---------------------
  #-----------------------------------------------
  # Optional: remove the bottom part of the figure
  #-----------------------------------------------
  if ( $cut_bottom ); then
    convert $TMP/figure.png -crop +0-${cut_bottom_pixels} +repage $TMP/figure.png
  fi
  #---------------------------------------------------------
  # set figure as figure_and_footer
  #---------------------------------------------------------
  mv $TMP/figure.png $TMP/fig_and_footer.png
fi
#------------------------------------------
# Cut the upper part of the image to remove old title
#------------------------------------------
if ( $cut_title ); then
  convert $TMP/fig_and_footer.png -crop +0+${cut_title_pixels} +repage $TMP/fig_and_footer.png
fi
#------------------------------------------
# Add title if needed
#------------------------------------------
if [[ -v TITLE ]]
then 
  if [[ $add_strip_below_title -gt 0 ]]; then
     convert -size x${add_strip_below_title} xc:white $TMP/white_strip.png
     montage $TMP/white_strip.png $TMP/fig_and_footer.png -tile 1x2 -geometry +0+0 $TMP/fig_and_footer_and_strip.png
  else
     mv $TMP/fig_and_footer.png $TMP/fig_and_footer_and_strip.png
  fi
  convert $TMP/fig_and_footer_and_strip.png -background white -gravity Center -pointsize $titsize_rescaled -font Arial -define pango:center=true pango:"<b>$TITLE</b>" +swap -append $TMP/fig_footer_and_header.png    
else
  mv $TMP/fig_and_footer.png $TMP/fig_footer_and_header.png
fi
#------------------------------------------
# Add space above the title 
#------------------------------------------
convert -size x${add_strip_above_title} xc:white $TMP/space.png
montage $TMP/space.png $TMP/fig_footer_and_header.png  -tile 1x2 -geometry +0+0 $TMP/fig_footer_and_header.png
#------------------------------------------
# Move final result to OUTFILE
#------------------------------------------
mv $TMP/fig_footer_and_header.png $OUTFILE
