#!/bin/bash

set -e

. script/build.config

PROJECT_NAME="ios/RetroArch_iOS.xcodeproj"

xcodebuild clean -project $PROJECT_NAME
rm -rf build

if [ -z "$NOCODESIGN" ] ; then
  # Fetch the UUID of the provisioning profile and install the profile
  # https://github.com/sharpland/mobileprovisionParser
  # http://idevblog.info/mobileprovision-files-structure-and-reading/
  PROVISION_UUID=`script/mobileprovisionParser -f "$PROVISIONING" -o UUID`
  cp "$PWD/$PROVISIONING" ~/Library/MobileDevice/Provisioning\ Profiles/"$PROVISION_UUID".mobileprovision

  xcodebuild -verbose -sdk iphoneos -configuration Release CODE_SIGN_IDENTITY="${CODE_SIGN_IDENTITY}" PROVISIONING_PROFILE="$PROVISION_UUID" -project $PROJECT_NAME

  echo "CODESIGNING DYNAMIC LIBRARIES AND BUILDING IPA"
  codesign -fs "$CODE_SIGN_IDENTITY" $BUILD_PATH/RetroArch.app/modules/*.dylib

  xcrun -sdk iphoneos PackageApplication "$BUILD_PATH/RetroArch.app" -o "$BUILD_PATH/RetroArch.ipa" --sign "$CODE_SIGN_IDENTITY" --embed "$BUILD_PATH/RetroArch.app/embedded.mobileprovision"
else
  xcodebuild -verbose -sdk iphoneos -configuration Release -project $PROJECT_NAME
  echo "Building for Jailbroken system"
fi

echo "######### RetroArch build Complete!! #########"
echo "You can find the resulting app in the $BUILD_PATH directory.\n"
