#!/usr/bin/env bash
#
# 2D or 3D, low or high resolution, ODM assembly script
# xxx git version macro goes here

# to do 
# 	separate script to move a set of output directories to /cluster/fieldscience/artifacts/image-analysis/...
# 		move.sh 
# 			cp nohup-$RUNID to destdir
# 			${var#*SubStr}
#
#	interface - image source dir, dest dir prefix, 
# 	command line overrides for resolution paramters (fast field assembly mode) 
# 	check parameters and bail if any are not set
# 	is $pwd required for Docker or can we use absolute paths?
# 	why not python?
#	clean _.DJI... files, prune low ones from each end?

# --crop = 0 disable, try 1-5 or so (by meters)

set -euo pipefail
VERBOSE=false

# Usage information. Gets displayed if the arguments are not entered correctly.
usage()
{
cat << EOF
usage example: nohup ./assemble-odm.sh -r ultra -b roundhouse-skalanes -d 2 -e dkvart17@earlham.edu -v &
-r    | --resolution      (required)            The quality of the mesh. Available options: medium, high, ultra
-b    | --basename        (required)            The base of the directory where the images live. If the name of the directory
                                                is roundhouse-skalanes-images then the base is roundhouse-skalanes
-d    | --dimensions      (required)            Produces either 2D or 3D meshes. Available options: 2, 3
-e    | --email           (required)            Email address where the log will be sent
-v    | --verbose                               More debugging output
-h    | --help                                  Brings up usage
EOF
}


# Parse the command line arguments.
while [[ $# -gt 0 ]]
do
key="$1"

case $key in
    -r|--resolution)
    	RESOLUTION="$2"
    	shift # past argument
    	shift # past value
    ;;
    -b|--basename)
    	BASENAME="$2"
    	shift # past argument
    	shift # past value
    ;;
    -d|--dimensions)
    	DIMENSIONS="$2"
    	shift # past argument
    	shift # past value
    ;;
    -e|--email)
		EMAIL_ADDRESS="$2"
		shift
		shift
	;;
	-v|--verbose)
		VERBOSE=true
		shift
	;;
    -h|--help)
    	usage
    	exit 0
    ;;
    *)    # unknown option
    shift # past argument. Just ignore the rest
    ;;
esac
done


if [[ -z ${RESOLUTION+x} || -z ${BASENAME+x} || -z ${DIMENSIONS+x} || -z ${EMAIL_ADDRESS+x} ]]; then
	echo "You didn't set the parameters correctly!"
	usage
	exit 1
fi

SOURCE_IMAGES=$BASENAME-images
RUNID=$DIMENSIONS-$RESOLUTION

# mesh quality
if [[ ( "$RESOLUTION" == "medium" ) ]]; then
	MNF=12000
	MS=150000
	MOD=10
	QUALITY="medium"
elif [[ ( "$RESOLUTION" == "high" ) ]]; then
	MNF=24000
	MS=300000
	MOD=11
	QUALITY="high"
elif [[ ( "$RESOLUTION" == "ultra" ) ]]; then
	MNF=36000
	MS=400000
	MOD=12
	QUALITY="ultra"	

else
	echo "unknown RESOLUTION" $RESOLUTION
	usage
	exit 1
fi


if [[ ! -d $SOURCE_IMAGES ]]; then
	echo "Directory $SOURCE_IMAGES does not exist!"
	usage
	exit 1
fi


# dimensions 
if [[ ( "$DIMENSIONS" == 2 ) ]]; then 
	DIMS="--fast-orthophoto --orthophoto-png"

elif [[ ( "$DIMENSIONS" == 3 ) ]]; then 
	DIMS="--dsm"

else 
	echo "unknown DIMENSIONS" $DIMENSIONS
	usage
	exit 1
fi

cat << EOF
Initializing ODM with the following parameters..
================================================
RESOLUTION: $RESOLUTION
SOURCE_IMAGES: $SOURCE_IMAGES
DIMENSIONS: $DIMENSIONS
EMAIL_ADDRESS: $EMAIL_ADDRESS
================================================
EOF


# directories and the rest of the command line
COMMAND_LINE="docker run --detach \
-v \"$(pwd)/$SOURCE_IMAGES:/code/images\" \
-v \"$(pwd)/$BASENAME-$RUNID-odm_orthophoto:/code/odm_orthophoto\" \
-v \"$(pwd)/$BASENAME-$RUNID-odm_texturing:/code/odm_texturing\" \
-v \"$(pwd)/$BASENAME-$RUNID-odm_dem:/code/odm_dem\" \
-v \"$(pwd)/$BASENAME-$RUNID-odm_meshing:/code/odm_meshing\" \
-v \"$(pwd)/$BASENAME-$RUNID-odm_georeferencing:/code/odm_georeferencing\" \
opendronemap/odm $DIMS \
--min-num-features $MNF --mesh-size $MS --mesh-octree-depth $MOD \
--pc-quality $QUALITY --feature-quality $QUALITY --time"


if [ "$VERBOSE" = true ]; then
	echo "Running the command below ==>"
	echo "$COMMAND_LINE"
fi

CID=$(eval "$COMMAND_LINE")

echo "CID: $CID"
echo "basename-runid: $BASENAME $RUNID"

docker wait $CID
docker logs $CID
docker rm $CID

# scp assemble-odm.sh earlhamfieldsci@192.168.8.101:~/Desktop
mv nohup.out $BASENAME-$RUNID-log.out

echo "" | mailx -a nohup.out -s "$BASENAME-$RUNID complete on $HOSTNAME" $EMAIL_ADDRESS

exit 0

# basename plus runid, should source and dest be automated at all? (prefix, only for moving ODM runs
# odm-run and odm-move )
# for file in Skalanes-Arch-1-VLI-2019-2D*; do sudo mv $file /cluster/fieldscience/artifacts/image-analysis/Skalanes/Arch-1-VLI-2019/${file##*2019-}; done
# mv nohup-Skalanes-Arch-1-VLI-2019-2D.out /cluster/fieldscience/artifacts/image-analysis/Skalanes/Arch-1-VLI-2019/
