#!/bin/bash

# the following environment variables must be set
: ${ROOT_DIR?} ${BUILD_DIR?} ${PACKAGE_LBL?} ${PACKAGE_DIR?} ${PACKAGE_NAME?} ${PACKAGE_SEP?}

# more variables
APP_PATH="${BUILD_DIR}/${GCS_SMALL_NAME}_release/${GCS_BIG_NAME}.app"
OUT_FILE="${PACKAGE_DIR}/../${PACKAGE_NAME}${PACKAGE_SEP}${PACKAGE_LBL}${PACKAGE_SEP}osx.dmg"

SRC_DIR="${PACKAGE_DIR}/src"
APPLICATION_NAME="${GCS_BIG_NAME}.app"
VOL_NAME="${GCS_BIG_NAME}"
# cleanup previous build
rm -rf "${SRC_DIR}"
rm -rf "${OUT_FILE}"

# copy base dmg structure
cp -r "${ROOT_DIR}/package/osx/dmg/" "${SRC_DIR}"
sed -i '' s/@URL@/$(echo ${WIKI_URL_ROOT} | sed -e 's/\\/\\\\/g' -e 's/\//\\\//g' -e 's/&/\\\&/g')/ "${SRC_DIR}/Getting Started.webloc"

# packaging goes here
cp -a "${APP_PATH}" "${SRC_DIR}"

mkdir "${SRC_DIR}/Docs/"
mkdir "${SRC_DIR}/Utilities/"

cp "${BUILD_DIR}/uavobject-synthetics/matlab/OPLogConvert.m" "${SRC_DIR}/Utilities/"
cp "${ROOT_DIR}/WHATSNEW.txt" "${SRC_DIR}"
cp "${ROOT_DIR}/README.md" "${SRC_DIR}/Docs/README.txt"
cp "${ROOT_DIR}/MILESTONES.txt" "${SRC_DIR}/Docs/"
cp "${ROOT_DIR}/LICENSE.txt" "${SRC_DIR}/Docs/"
cp "${ROOT_DIR}/GPLv3.txt" "${SRC_DIR}/Docs/"

"${ROOT_DIR}/package/osx/libraries" \
    "${SRC_DIR}/${APPLICATION_NAME}" || exit 1

"${ROOT_DIR}/package/osx/create-dmg/create-dmg" \
--volname "${VOL_NAME}" \
--volicon "${ROOT_DIR}/package/osx/VolumeIcon.icns" \
--background "${ROOT_DIR}/package/osx/background.png" \
--window-size 600 500 \
--icon-size 60 \
--icon "Getting Started.webloc" 110 380 \
--hide-extension "Getting Started.webloc"  \
--icon "Docs" 250 380 \
--icon "WHATSNEW.txt" 400 380 \
--icon "Utilities" 500 380 \
--icon "${APPLICATION_NAME}" 150 215 \
--hide-extension "${APPLICATION_NAME}" \
--app-drop-link 450 215 \
--no-internet-enable \
"${OUT_FILE}" \
"${SRC_DIR}"
