#!/bin/bash

PATH=$PATH:$(dirname "$0")

# Check for required programs before starting 
requiredPrograms=( "montage" )
requiredOk=1
for prg in "${requiredPrograms[@]}"; do
    path=$(which $prg)
    if [[ "" == "$path" ]]; then
        requiredOk=0
        echo "ERROR: Required program '$prg' not found" >&2
    fi
done

if [[ $requiredOk -eq 0 ]]; then
    echo "       Please provide those programs in order to use this script" >&2
    exit 2
fi


# General help that is shown whenever the script cannot be run because the user
# did not provide sufficient parameters
function showHelp {
    cmd=$(basename "$0")
    echo ""
    echo "        -----===== $cmd =====-----"
    echo ""
    echo "   \"$cmd --of=OUTFILE [OPTIONAL PARAMETERS] IMAGE1 [IMAGE2 [IMAGE3 [...]]]\""
    echo ""
    echo "Concatenates the images in the given order and writes the result to the file"
    echo "specified by --of"
    echo ""
    echo "Obligatory parameters:"
    echo " --of=         The out-file, meaning the file to write the concatenated image "
    echo "               to. This file will be overwritten without notice."
    echo ""
    echo "Optional parameters:"
    echo " --background= The color of the background if the pictures do not have the same"
    echo "               size. (default: black)"
    echo " --align=      Vertical alignment of images that are smaller that the biggest "
    echo "               image given"
    echo ""
    echo "Example: "
    echo "   \"$cmd --of=bg.png --background=black one.jpg two.jpg\""
    echo ""
    echo "Exit-Codes:"
    echo "  0 - Everything is fine"
    echo "  1 - Wrong parameters"
    echo "  2 - File parameter is no file"
    echo "  3 - File parameter is no image"
    echo "  3 - Not enough file parameters"
    echo " 11 - Image concatenating failed (imagemagick error)"
    echo " 23 - I am watching you."
    echo " 42 - Please state the question."
    echo " 99 - The requested feature is not (yet) implemented"
    echo ""
    
}

## Used to output certain information only in verbose-mode
#function echoIfVerbose {
#    if [[ $verbose -eq 1 ]]; then
#        echo $@
#    fi
#}

# initializing variables
exitStatus=0
background="black"
outFile=""
inFiles=()
#verbose=0

# Analyze given parameters
for param in "$@"; do
    knownParam=0

    if [[ "${param:0:5}" == "--of=" ]]; then
        knownParam=1
        outFile="${param:5}"
    fi
   
    if [[ "${param:0:2}" != "--" ]]; then
        knownParam=1
        if [[ -f "$param" ]]; then
            type=$(file -b -i "$param" | cut -c 1-5)
            # Check if the file is an image
            if [[ "image" == "$type" ]]; then
                inFiles[${#inFiles[*]}]=$param
            else
                echo "ERROR: Parameter is not an image. Type: '$type' File: '$param'" >&2
                exitStatus=3
            fi
        else
            echo "ERROR: Parameter is not a file: '$param'" >&2
            exitStatus=2
        fi
    fi

    #if [[ "${param:0:9}" == "--verbose" ]]; then
    #    knownParam=1
    #    verbose=1
    #fi

    if [[ "${param:0:13}" == "--background=" ]]; then
        knownParam=1
        background=${param:13}
        exitStatus=99
    fi

    if [[ "${param:0:8}" == "--align=" ]]; then
        knownParam=1
        align=${param:8}
        echo "ERROR: --align is currently not implemented!" >&2
        exitStatus=99
    fi

    # Check for unknown parameters
    # Has to be at the end of this loop
    if [[ $knownParam -eq 0 ]]; then
        echo "ERROR: Unknown Parameter '$param'" >&2
        exitStatus=4
    fi
done

if [[ "$outFile" == "" ]]; then
    echo "ERROR: Obligatory Parameters not given" >&2
    echo "       Please provide an out-file (of) parameters" >&2
    exitStatus=1
fi

if [[ ${#inFiles[*]} -lt 2 ]]; then
    echo "ERROR: Not enough file parameters given" >&2
    echo "       Please provide at least two images to concatenate" >&2
    exitStatus=1
fi


if [[ $exitStatus -ne 0 ]]; then
    ## Code for debugging parameters
    #echo "Parameters received:"
    #x=0
    #while [[ "$1" != "" ]]; do
    #   let "x = $x + 1"
    #   echo "$x: $1"
    #   shift
    #done

    showHelp
    exit $exitStatus
fi


montage "${inFiles[@]}" -tile x1 -geometry +0+0\> -background $background -mode Concatenate $outFile
status=$?

if [[ $status -ne 0 ]]; then
    echo "ERROR: ImageMagick has failed to concatenate the images. IM exit status: $status " >&2
    exit 11
fi

