#!/bin/sh
# Copyright 2020 VMWare, Inc. All rights reserved.
#
# Usage:
#   * In the project editor, select your app target.
#   * Click "Build Phases" at the top of the project editor.
#   * Click "Add Build Phase (+)" in the top left corner.
#   * Choose "New Run Script Phase"
#   * Rename the Run Script Phase to 'dSYM Upload' or similar
#   * Paste the following script into the dark text box. You will have to
#     uncomment the lines (remove the #s) of course.
#   * In the 'Input File Lists' section, add the dsym_upload.xcfilelist file.
#
# --- SCRIPT BEGINS ON NEXT LINE, COPY AND EDIT FROM THERE ---
# APP_ID="<YOUR_APP_ID>"
# CREDENTIALS_FILE="${SRCROOT}/<PATH_TO_SCRIPT>/service-account-dsymupload@<UUID>.data.vmwservices.com.json"
# source "${SRCROOT}"/<PATH_TO_SCRIPT>/dsym_upload.sh
# --- END OF SCRIPT ---
#
# The script can also be executed outside of XCode as a standalone script
# sh dsym_upload.sh -i <YOUR_APP_ID> -c <PATH_TO_CREDENTIALS_FILE> -b <YOUR_APP_VERSION> <PATH_TO_DSYM_FILE>/YourApp.app.dSYM
#
# YOUR_APP_ID       - The app ID for your app as seen in the WS1 Intelligence console
# YOUR_APP_VERSION  - The version string for the app. This is the short bundle version string defined in the info.plist file.
# CREDENTIALS_FILE  - The credential file which is generated and downloaded from the WS1 Intelligence console. 
#                     This file will have a name such as: service-account-dsymupload\@<UUID>.data.vmwservices.com.json
# PATH_TO_DSYM_FILE - Path the the dSYM file that needs to be uploaded.
#
################################################################################
# Advanced Settings
#
# You can override these directly in XCode in your Run Script Build Phase, or
# change the defaults below.

# Should simulator builds cause symbols to be uploaded?
UPLOAD_SIMULATOR_SYMBOLS=${UPLOAD_SIMULATOR_SYMBOLS:=1}

# This setting determines whether or not your build will fail if the dSYM was
# not uploaded properly to WS1 Intelligence servers.
#
# You may wish to change this setting if you are building without internet
# access, or otherwise are having difficulty connecting to WS1 Intelligence
# servers.
REQUIRE_UPLOAD_SUCCESS=${REQUIRE_UPLOAD_SUCCESS:=1}

################################################################################
# You should not need to edit anything past this point.
################################################################################

SCRIPT_VERSION="6.0.3"

#
#  Verbose mode prints extra messages via this function
#
function verbose() {
  message="$1"
  if $VERBOSE; then
    echo "$message"
  fi
}

#
#  cleanup function removes TMP_UPLOAD_DIR directory
#
TMP_UPLOAD_DIR=""
function cleanup() {
  # Initially, TMP_UPLOAD_DIR="" and MKTEMP_EXE hasn't been called yet.
  # Farther into the script, MKTEMP_EXE is defined and TMP_UPLOAD_DIR
  # directory may be created.  Remove TMP_UPLOAD_DIR directory if we
  # created TMP_UPLOAD_DIR.
  if [ "$TMP_UPLOAD_DIR" != "" ] && [ -d "$TMP_UPLOAD_DIR" ]; then
    rm -rf "$TMP_UPLOAD_DIR"
  fi
  verbose "cleanup completed"
}

#
#  exitWithMessageAndCode function prints message and exits
#
function exitWithMessageAndCode() {
  message="$1"
  echo "$message"
  cleanup
  exit ${2}
}

#
#  Check requirements are existing executable files
#
function check_exec() {
  path="$1"
  exec="$2"
  if [[ ! -f "$path" ]]; then
    exitWithMessageAndCode "File '$exec' is not found. ABORTING." 1
  elif [[ ! -x "$path" ]]; then
    exitWithMessageAndCode "File '$path' is not executable. ABORTING." 1
  fi
}

function setup_for_macosx() {
  MKTEMP_EXE="/usr/bin/mktemp"
  check_exec "$MKTEMP_EXE" "mktemp"

  PLISTBUDDY_EXE="/usr/libexec/PlistBuddy"
  check_exec "$PLISTBUDDY_EXE" "PlistBuddy"

  RM_EXE="/bin/rm"
  check_exec "$RM_EXE" "rm"

  ZIP_EXE="/usr/bin/zip"
  check_exec "$ZIP_EXE" "zip"

  JQ_EXE=`which jq`
  check_exec "$JQ_EXE" "jq"

  CURL_EXE=`which curl`
  check_exec "$CURL_EXE" "curl"

  CAT_EXE="/bin/cat"
  check_exec "$CAT_EXE" "cat"
}

function exit_unsupported_os() {
  fail "ERROR: Your OS [$1] is not supported - use Mac OSX";
}

REGION_CODE=""
function set_region {
  verbose "Establishing region for app ID..."
  REGION_CODE=$(curl https://api.na1.region.data.vmwservices.com/v1/appids/${APP_ID} | jq -r '.region_code')
  
  if [ -z "$REGION_CODE" ]; then
    exitWithMessageAndCode "Missing region code. ABORTING." 1
  fi

  if [ "$REGION_CODE" == "null" ]; then
    exitWithMessageAndCode "Region response missing region code. ABORTING." 1
  fi

  verbose "Determined region: ${REGION_CODE}"
}

#
#  Generate Access Token based on credentials file content
#
function generate_access_token {
  verbose "Parsing credentials file for access token."

  CLIENT_ID=$(jq -r '.clientId' "${CREDENTIALS_FILE}")
  CLIENT_SECRET=$(jq -r '.clientSecret' "${CREDENTIALS_FILE}")
  TOKEN_ENDPOINT=$(jq -r '.tokenEndpoint' "${CREDENTIALS_FILE}")

  verbose "Generating access token..."

  ACCESS_TOKEN=$(curl -f -u "$CLIENT_ID:$CLIENT_SECRET" "$TOKEN_ENDPOINT" -d "" | jq -r .access_token)

  verbose "Access token generated."

  verbose "Client ID ${CLIENT_ID}"
  verbose "Client Secret ${CLIENT_SECRET}"
  verbose "Token Endpoint ${TOKEN_ENDPOINT}"
  verbose "Access Token ${ACCESS_TOKEN}"
}

#
#  Upload the app dSYM zip file to WS1Intelligence
#
function upload_symbolic_file {

  if [ -z "$ACCESS_TOKEN" ]; then
    exitWithMessageAndCode "Missing access token. ABORTING." 1
  fi

  if [ -z "$APP_ID" ]; then
    exitWithMessageAndCode "Missing app ID. Please define APP_ID. ABORTING." 1
  fi

  if [ -z "$MARKETING_VERSION" ]; then
    exitWithMessageAndCode "Missing app version. Please define MARKETING_VERSION. ABORTING." 1
  fi

  verbose "Uploading file. Please wait..."
  verbose "Symbol File to upload: $SYMBOL_FILE"

  CURL_RESPONSE=$(curl --write-out %{http_code} --silent --output /dev/null -v -i -F "user-file=@$SYMBOL_FILE;type=application/zip" -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Type: multipart/form-data" "${TARGET_API}/v1/crash/symbols/${PLATFORM}/${APP_ID}/${MARKETING_VERSION}")

  if [[ $CURL_RESPONSE < 300 ]] && [[ $CURL_RESPONSE -ge 200 ]]; then
    # Success
    verbose "Symbol File upload successful"
  else
    if [ $REQUIRE_UPLOAD_SUCCESS -eq 1 ]; then
      verbose "Symbol File upload failed with result ${CURL_RESPONSE}, exiting..."
      exit 1
    fi
  fi
}

#
#  main():
#
PROG_NAME=`basename $0`
UNAME=`uname -s`
case "$UNAME" in
  Darwin*)  setup_for_macosx        ;;
  *)     exit_unsupported_os "$UNAME"  ;;
esac

################################################################
# Parsing the command line.
################################################################

function terse_usage() {
  if [ $# -gt 0 ]; then
    echo $@
  fi

  echo "     ${PROG_NAME} -h"
  echo "     ${PROG_NAME} [-i appId] [-c credentialsJson] [-b shortBundleVersion] [-v] YourApp.dSYM"
}

function usage() {
  echo
  echo "NAME"
  echo ""
  echo "     ${PROG_NAME} -- Uploads a *.dSYM to WS1 Intelligence for crash symbolication."
  echo
  echo "SYNOPSIS"
  echo ""
  terse_usage
  echo
  echo "DESCRIPTION"
  echo ""
  echo "     The ${PROG_NAME} script is used to upload an iOS *.dSYM created by Xcode IDE"
  echo "     when Xcode builds an iOS app or, later on, upload an iOS *.dSYM"
  echo "     retrieved via the Xcode Organizer 'Download dSYMS...' button."
  echo ""
  echo "OPTIONS"
  echo ""
  echo "     The options are as follows:"
  echo "     -i      App ID.  The App ID is a 24 or 40 digit character string."
  echo "     -c      Customer credentials file. This is generated by the WS1 Intelligence portal."
  echo "     -b      Short bundle version string. This should match the version for any missing"
  echo "             symbols indicated by the WS1 Intelligence portal."
  echo "     -h      Help. Print usage information."
  echo "     -v      Verbose.  Print extra script information to assist diagnosis of any issues."
  echo ""
  echo "EXAMPLES"
  echo ""
  echo "     To upload a *.dSYM, using an interactive interface:"
  echo "             export APP_ID=\"<YOUR_APP_ID>\""
  echo "             export CREDENTIALS_FILE=\"<PATH_TO_CREDENTIALS_FILE>/service-account-dsymupload@<UUID>.data.vmwservices.com.json\""
  echo "             export MARKETING_VERSION=\"<YOUR_APP_VERSION>\""
  echo "             sh dsym_upload.sh <PATH_TO_DSYM>/YourApp.dSYM"
  echo ""
  echo "     To upload a *.dSYM, using an Xcode build phase run script:"
  echo "             APP_ID=\"<YOUR_APP_ID>\""
  echo "             CREDENTIALS_FILE=\"<PATH_TO_CREDENTIALS_FILE>/service-account-dsymupload@<UUID>.data.vmwservices.com.json\""
  echo "             source \${SRCROOT}/<PATH_TO_SCRIPT>/dsym_upload.sh"
  echo ""
  echo "     To upload a *.dSYM, using a command line interface:"
  echo "             sh dsym_upload.sh -i \"<YOUR_APP_ID>\" -c \"<PATH_TO_CREDENTIALS_FILE>/service-account-dsymupload\@<UUID>.data.vmwservices.com.json\" -b \"<YOUR_APP_VERSION>\" \"<PATH_TO_DSYM>/TestApp.app.dSYM\""
  echo ""
}

if [ $# -eq 1 ] && [ $1 = "-h" ]; then
  usage
  exit 0
fi

# NOTE: Return absolute path. Limitation: Doesn't resolve symlinks,
# but is step forward.
realpath() {
  [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}

DSYM_SRC=${DSYM_SRC:=""}
APP_ID=${APP_ID:=""}
MARKETING_VERSION=${MARKETING_VERSION:=""}
VERBOSE=true

while getopts i:c:b:hv opt; do
  case $opt in
    i)
      APP_ID="$OPTARG"
      ;;
    c)
      CREDENTIALS_FILE="$OPTARG"
      ;;
    b)
      MARKETING_VERSION="$OPTARG"
      ;;
    h)
      usage
      exit 0
      ;;
    v)
      VERBOSE=true
      ;;
  esac
done

if [ $OPTIND = $# ]; then
  DSYM_SRC=${@:$OPTIND:1}
fi

verbose "DSYM_SRC == ${DSYM_SRC}"
verbose "APP_ID == ${APP_ID}"
verbose "MARKETING_VERSION == ${MARKETING_VERSION}"

################################################################
# Acquire TMP_UPLOAD_DIR, DSYM_ROOT, and DSYM_ZIP_FPATH
################################################################

verbose "Acquire TMP_UPLOAD_DIR, DSYM_ROOT, and DSYM_ZIP_FPATH"
verbose "Script version ${SCRIPT_VERSION}"
verbose "Curl version $(curl --version)"

if [ ! "${DWARF_DSYM_FILE_NAME}" ]; then
  verbose "DWARF_DSYM_FILE_NAME is undefined"
  if [ ! "${DSYM_SRC}" ]; then
    verbose "DSYM_SRC is undefined"
    exitWithMessageAndCode "dSYM source not found: ${DSYM_SRC}" 1
  else
    # Assume running script inside Terminal window
    verbose "DSYM_SRC is defined"
    MKTEMP_EXE="/usr/bin/mktemp"
    TMP_UPLOAD_DIR=`$MKTEMP_EXE -d -t ws1intelligence_symbol_upload`
    DSYM=`realpath "${DSYM_SRC}"`
    DSYM_FILE=`basename "${DSYM}"`
  fi
else
  # Assume running script inside Xcode IDE
  VERBOSE=true
  verbose "DWARF_DSYM_FILE_NAME is defined"

  TMP_UPLOAD_DIR="${TARGET_TEMP_DIR}/ws1intelligence"
  mkdir -p "${TMP_UPLOAD_DIR}"

  DSYM_SRC="${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}"
  DSYM_FILE="${DWARF_DSYM_FILE_NAME}"
  # Display build info
  BUNDLE_VERSION=$(/usr/libexec/PlistBuddy -c 'Print CFBundleVersion' "${INFOPLIST_FILE}")
  BUNDLE_SHORT_VERSION=$(/usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' "${INFOPLIST_FILE}")
  
  # Since Xcode 11, app info.plist will refer to $(MARKETING_VERSION) for the
  # BUNDLE_SHORT_VERSION value. If MARKETING_VERSION is non-empty, we will use
  # that. If it's not defined or not set, then fall back to BUNDLE_SHORT_VERSION
  # from the info.plist file. Newer apps should have MARKETING_VERSION set, while
  # older apps may still have the version set directly in the plist file.
  if [ -z "$MARKETING_VERSION" ]; then
    MARKETING_VERSION=${BUNDLE_SHORT_VERSION}
  fi

  verbose "Product Name: ${PRODUCT_NAME}"
  verbose "Version: ${MARKETING_VERSION}"
  verbose "Build: ${BUNDLE_VERSION}"
fi

DSYM_ROOT=`echo ${DSYM_FILE} | sed -e "s/\.dSYM$//g"`
DSYM_ZIP_FPATH="${TMP_UPLOAD_DIR}/${DSYM_ROOT}.zip"

verbose "TMP_UPLOAD_DIR: ${TMP_UPLOAD_DIR}"
verbose "DSYM_ROOT: ${DSYM_ROOT}"
verbose "DSYM_ZIP_FPATH: ${DSYM_ZIP_FPATH}"

################################################################
# Upload to WS1Intelligence
################################################################

# Possibly bail if this is a simulator build
if [ "$EFFECTIVE_PLATFORM_NAME" == "-iphonesimulator" ]; then
  if [ $UPLOAD_SIMULATOR_SYMBOLS -eq 0 ]; then
    exitWithMessageAndCode "skipping simulator build" 0
  fi
fi

################################################################
# Compress app symbol file
################################################################

# create dSYM .zip file
verbose "dSYM Source: ${DSYM_SRC}"

if [ ! -d "$DSYM_SRC" ]; then
  exitWithMessageAndCode "dSYM source not found: ${DSYM_SRC}" 1
fi

pushd ${DWARF_DSYM_FOLDER_PATH}
(/usr/bin/zip --recurse-paths "${DSYM_ZIP_FPATH}" "${DSYM_FILE}") || exitWithMessageAndCode "err: Failed creating zip." 1
popd

verbose "dSYM zip archive created ${DSYM_ZIP_FPATH}"

################################################################
# Upload to WS1Intelligence
################################################################

verbose "WS1Intelligence dSYM upload starting..."

verbose "Uploading ${DSYM_ZIP_FPATH}"
verbose "Credentials file ${CREDENTIALS_FILE}"
verbose "Version ${MARKETING_VERSION}"

APP_ID=${APP_ID:=""}
CREDENTIALS_FILE=${CREDENTIALS_FILE:=""}
SYMBOL_FILE=${DSYM_ZIP_FPATH}
PLATFORM="ios"

set_region;

TARGET_API="https://api.${REGION_CODE}.data.vmwservices.com"

generate_access_token;
upload_symbolic_file;

################################################################
# Cleanup
################################################################

# Remove temp dSYM archive
verbose "Removing temporary dSYM.zip archive."

/bin/rm -f "${DSYM_ZIP_FPATH}"
if [ "$?" -ne 0 ]; then
  exitWithMessageAndCode "Error removing temporary dSYM.zip archive." 1
fi

verbose "WS1Intelligence dSYM upload complete."

