#!/bin/bash

# Assumes we've run gs3-setup.sh
pushd $GSDL3SRCHOME/ext
version=3.5.28


#https://sourceforge.net/projects/djvu/files/DjVuLibre_MacOS/3.5.28%2B4.12-universal/DjVuLibre-3.5.28%2BDjView-4.12-universal-2.dmg/download
wget --no-check-certificate -O djvulibre.dmg https://sourceforge.net/projects/djvu/files/DjVuLibre_MacOS/${version}+4.12-universal/DjVuLibre-${version}+DjView-4.12-universal-2.dmg/download


# https://osxdaily.com/2011/12/17/mount-a-dmg-from-the-command-line-in-mac-os-x/
# This does not complete storing the output of the cmd, instead saving cmd output to file works
#mounted_as=`hdiutil attach djvulibre.dmg`
hdiutil attach djvulibre.dmg > mounted.out 2>&1 

# To unmount, we need the 1st field of the final line of the output of mounting with hdiutil 
# https://community.hpe.com/t5/operating-system-linux/awk-to-print-last-line/m-p/5064123#M94447
# "This script saves field 1 of the last line" (of the hdiutil attach output):
# The mounted_as variable didn't store the full cmd output the 1st time we mount after downloading
# so have to save the cmd output to a file, then apply awk to retrieve 1st field of final line
#echo $mounted_as | awk '
#mounted_as=$(echo $mounted_as | awk '
mounted_as=$(cat mounted.out | awk '
{
SAVE = $1
}
END { print SAVE } ')

echo "output - mounted as: $mounted_as"


# If copying into the Mac Applications folder (as advised in the tutorial)
#cp -r /Volumes/DjVuLibre-${version}+DjView-4.12-universal-2/DjView.app /Volumes/Macintosh\ HD/Applications/.
# But we can copy the entire djvulibre suite into local GS3 space, and djvutxt appears to run.
# We can then run it as $GSDL3SRCHOME/ext/djvulibre/Contents/MacOS/djvutxt
#cp -r /Volumes/DjVuLibre-${mac_suffix_title}-2/DjView.app/ ext/djvulibre

success=true
dmg_file=/Volumes/DjVuLibre-${version}+DjView-4.12-universal-2/DjView.app/Contents/MacOS/djvutxt
if [ -f "$dmg_file" ]; then
    echo "*** dmg mounted: $dmg_file exists."
    echo "*** Copying .app contents across to $GSDL3SRCHOME/ext/djvulibre..."
    cp -r /Volumes/DjVuLibre-${version}+DjView-4.12-universal-2/DjView.app $GSDL3SRCHOME/ext/djvulibre
else
    echo "### The dmg doesn't appear to be mounted: missing $dmg_file"
    sucess=false
fi

echo "*** Unmounting $dmg (hdiutil detach $mounted_as)"
hdiutil detach $mounted_as
popd

# use absolute paths
if [ "x$success" = "xtrue" ] ; then
    echo "*** Deleting tmp file ext/mounted.out"
    rm -f $GSD3SRCHOME/ext/mounted.out
    
    echo "*** Can now run $GSDL3SRCHOME/ext/djvulibre/Contents/MacOS/djvutxt"
    
    echo "*** Deleting the ext/djvulibre.dmg"
    rm -rf $GSDL3SRCHOME/ext/djvulibre.dmg

    exit 0
else
    echo "Inspect djuvlibre.dmg and mounted.out in $GSDL3SRCHOME/ext to help track down issues"
    exit -1
fi


