#!/bin/bash
#
# (Above line comes out when placing in Xcode scheme)
#

cd "$(dirname "$0")"

get_abs_filename() {
  # $1 : relative filename
  echo "$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
}

PRODUCT_NAME="Buildbox"

if [ ! -f "${HOME}/.bugsplat.conf" ]
then
    echo "Missing bugsplat config file: ~/.bugsplat.conf"
    exit
fi

source "${HOME}/.bugsplat.conf"

if [ -z "${BUGSPLAT_USER}" ]
then
    echo "BUGSPLAT_USER must be set in ~/.bugsplat.conf"
    exit
fi

if [ -z "${BUGSPLAT_PASS}" ]
then
    echo "BUGSPLAT_PASS must be set in ~/.bugsplat.conf"
    exit
fi

APP=$(get_abs_filename "../../../..")
echo $APP
APP_VERSION=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${APP}/Contents/Info.plist")
BUGSPLAT_SERVER_URL=$(/usr/libexec/PlistBuddy -c "Print BugsplatServerURL" "${APP}/Contents/Info.plist")
BUGSPLAT_SERVER_URL=${BUGSPLAT_SERVER_URL%/}

UPLOAD_URL="${BUGSPLAT_SERVER_URL}/post/plCrashReporter/symbol/"

echo "App version: ${APP_VERSION}"

ARC_ROOT=$APP/../Packing/Buildbox.xcarchive
BB_COPY=$ARC_ROOT/Products/Applications/Buildbox.app
SYMBOLS_OUT=$ARC_ROOT/dSYMs/Buildbox.app.dSYM
mkdir -p $BB_COPY $SYMBOLS_OUT
echo "Copying BB..."
cp -r $APP/* $BB_COPY
echo "Extracting debug symbols..."
/usr/bin/dsymutil $BB_COPY/Contents/MacOS/Buildbox -o $SYMBOLS_OUT
cp $APP/../../../potion/Packing_Info.plist $ARC_ROOT/Info.plist
SCRIPTS_ROOT=$APP/../../../scripts
$SCRIPTS_ROOT/stringreplace -i $ARC_ROOT/Info.plist -f \
    "{{VERSION}}" -r "${APP_VERSION}"
$SCRIPTS_ROOT/stringreplace -i $ARC_ROOT/Info.plist -f \
    "{{DATE}}" -r "`date +"%Y-%m-%dT%XZ"`"

echo "Zipping..."
/bin/rm "/tmp/${PRODUCT_NAME}.xcarchive.zip"
echo `pwd`
cd "${APP}/../Packing/Buildbox.xcarchive"
/usr/bin/zip -r "/tmp/${PRODUCT_NAME}.xcarchive.zip" *
cd -

UUID_CMD_OUT=$(xcrun dwarfdump --uuid "${APP}/Contents/MacOS/${PRODUCT_NAME}")
UUID_CMD_OUT=$([[ "${UUID_CMD_OUT}" =~ ^(UUID: )([0-9a-zA-Z\-]+) ]] && echo ${BASH_REMATCH[2]})
echo "UUID found: ${UUID_CMD_OUT}"

echo "Signing into bugsplat and storing session cookie for use in upload"

COOKIEPATH="/tmp/bugsplat-cookie.txt"
rm "${COOKIEPATH}"
curl -b "${COOKIEPATH}" -c "${COOKIEPATH}" --data "currusername=${BUGSPLAT_USER}&currpasswd=${BUGSPLAT_PASS}" "${BUGSPLAT_SERVER_URL}/browse/login.php"

echo "Uploading /tmp/${PRODUCT_NAME}.xcarchive.zip to ${UPLOAD_URL}"

echo curl -i -b "${COOKIEPATH}" -c "${COOKIEPATH}" -F filedata=@"/tmp/${PRODUCT_NAME}.xcarchive.zip" -F appName="${PRODUCT_NAME}" -F appVer="${APP_VERSION}" -F buildId="${UUID_CMD_OUT}" $UPLOAD_URL
curl -i -b "${COOKIEPATH}" -c "${COOKIEPATH}" -F filedata=@"/tmp/${PRODUCT_NAME}.xcarchive.zip" -F appName="${PRODUCT_NAME}" -F appVer="${APP_VERSION}" -F buildId="${UUID_CMD_OUT}" $UPLOAD_URL
