#!/bin/sh

#  convertToHEIF
#  
#  Created by Alex Karahalios on 10/20/17.
#
# Based on http://jpgtoheif.com
#

# Where we placed our versions of required programs
#
PATH=/usr/local/bin:/opt/local/bin:$PATH

# Makes sure the program we need is installed
#
function require {
    _commandPath=$(which "$1")
    if [[ $_commandPath == "" ]]; then
        echo "Program $1 is required, but can't be found on path.  Aborting."
        exit 1
    fi
}

# Display usage if at least 1 argument not present
#
_self="${0##*/}"                    # Name of command (without path)
(( $# < 1 )) && { echo "Usage: $_self input-image"; exit 1;}

# Required programs:
#   ffmpeg
#   writerapp
#
require ffmpeg
require writerapp

_inputFile="$1"                     # Input file on command line
_inputFileNoExt="${_inputFile%.*}"  # Input filename with no extension
_outputFile="$_inputFileNoExt".heif # Output file has same name as input w/heif extension

# Create a proxy file name to show HEIF conversion progress
#
_conversionProxy="$_inputFileNoExt Converting….heif"

# Generate H.265 bitstream file
#
ffmpeg \
    -loglevel quiet \
    -threads 5 \
    -i "$_inputFile" \
    -crf 9 -preset slower -pix_fmt yuv420p \
    -f hevc \
    -y "$_conversionProxy"

# Create JSON config file for writerapp using the filenames we created
#
_JSONconfigFile=$(mktemp -t JSONconfig)
cat <<EOF >$_JSONconfigFile
{
    "general": {
        "output": {
            "file_path": "$_outputFile"
        },
        "brands": {
            "major": "mif1",
            "other": ["mif1", "heif", "hevc"]
            }
        },
        "content": [{
            "master": {
                "file_path": "$_conversionProxy",
                "hdlr_type": "pict",
                "code_type": "hvc1",
                "encp_type": "meta"
            }
        }]
}
EOF

writerapp $_JSONconfigFile

# Remove all the temp files we created
#
rm -f "$_conversionProxy" "$_JSONconfigFile"

