#!/bin/sh -e
set -x

OS=mac

if [[ -n "$APPLICATION" ]]; then
  echo "Create a keychain"
  security create-keychain -p nr4aGPyz Keys.keychain

  echo $APPLICATION | base64 -D -o /tmp/Application.p12
  echo $INSTALLER | base64 -D -o /tmp/Installer.p12

  security import /tmp/Application.p12 -t agg -k Keys.keychain -P aym9PKWB -A -T /usr/bin/codesign
  security import /tmp/Installer.p12 -t agg -k Keys.keychain -P aym9PKWB -A -T /usr/bin/codesign

  security list-keychains -s Keys.keychain
  security default-keychain -s Keys.keychain
  security unlock-keychain -p nr4aGPyz Keys.keychain
  security set-keychain-settings -l -u -t 13600 Keys.keychain
  security set-key-partition-list -S apple-tool:,apple: -s -k nr4aGPyz Keys.keychain

  DEV_APP_ID="Developer ID Application: Roland Rabien (3FS7DJDG38)"
  DEV_INST_ID="Developer ID Installer: Roland Rabien (3FS7DJDG38)"
fi

ROOT=$(cd "$(dirname "$0")/../.."; pwd)
cd "$ROOT"

if [ ! -d "juce" ]; then
  git clone https://github.com/WeAreROLI/JUCE.git --branch develop --single-branch juce
fi

# Get the hash
cd "$ROOT/juce"
HASH=`git rev-parse HEAD`
echo "Hash: $HASH"

# Get the Projucer
mkdir -p "$ROOT/ci/bin"
cd "$ROOT/ci/bin"
while true
do
  PROJUCER_URL=$(curl -s -S "https://projucer.rabien.com/get_projucer.php?hash=$HASH&os=$OS&key=$APIKEY")
  echo "Response: $PROJUCER_URL"
  if [[ $PROJUCER_URL == http* ]]; then
    curl -s -S $PROJUCER_URL -o "$ROOT/ci/bin/Projucer.zip"
    unzip Projucer.zip
    break
  fi
  sleep 15
done

$ROOT/ci/bin/Projucer.app/Contents/MacOS/Projucer --set-global-search-path osx defaultJuceModulePath "$ROOT/juce/modules" 
$ROOT/ci/bin/Projucer.app/Contents/MacOS/Projucer --resave "$ROOT/examples/Demo/Demo.jucer"
$ROOT/ci/bin/Projucer.app/Contents/MacOS/Projucer --resave "$ROOT/examples/Synth/Synth.jucer"
$ROOT/ci/bin/Projucer.app/Contents/MacOS/Projucer --resave "$ROOT/tools/notarize/notarize.jucer"

cd "$ROOT/examples/Demo/Builds/MacOSX"
xcodebuild -configuration Release GCC_TREAT_WARNINGS_AS_ERRORS=YES || exit 1

cd "$ROOT/examples/Synth/Builds/MacOSX"
xcodebuild -configuration Release GCC_TREAT_WARNINGS_AS_ERRORS=YES || exit 1

cd "$ROOT/tools/notarize/Builds/MacOSX"
xcodebuild -configuration Release GCC_TREAT_WARNINGS_AS_ERRORS=YES || exit 1

rm -Rf "$ROOT/ci/mac/bin"
mkdir -p "$ROOT/ci/mac/bin"
cp -R "$ROOT/examples/Demo/Builds/MacOSX/build/Release/Demo.app" "$ROOT/ci/mac/bin"
cp -R "$ROOT/tools/notarize/Builds/MacOSX/build/Release/notarize" "$ROOT/ci/mac/bin"

if [[ -n "$APPLICATION" ]]; then
  cd "$ROOT/ci/mac/bin"
  codesign --force -s "$DEV_APP_ID" -v "Demo.app" --deep --strict --options=runtime
  codesign --force -s "$DEV_APP_ID" -v "notarize" --deep --strict --options=runtime

  ./notarize Demo.app $APPLE_USER $APPLE_PASS
fi

zip -r Demo.zip Demo.app

rm -Rf Demo.app
