#!/bin/bash

export SCRIPT_DIR=$(dirname "$0")

##
## Configuration Variables
##

SCHEMES="$@"

config ()
{
    # The workspace to build.
    #
    # If not set and no workspace is found, the -workspace flag will not be passed
    # to `xctool`.
    #
    # Only one of `XCWORKSPACE` and `XCODEPROJ` needs to be set. The former will
    # take precedence.
    : ${XCWORKSPACE=$(find_pattern "*.xcworkspace")}

    # The project to build.
    #
    # If not set and no project is found, the -project flag will not be passed
    # to `xctool`.
    #
    # Only one of `XCWORKSPACE` and `XCODEPROJ` needs to be set. The former will
    # take precedence.
    : ${XCODEPROJ=$(find_pattern "*.xcodeproj")}

    # A bootstrap script to run before building.
    #
    # If this file does not exist, it is not considered an error.
    : ${BOOTSTRAP="$SCRIPT_DIR/bootstrap"}

    # Extra options to pass to xctool.
    : ${XCTOOL_OPTIONS="RUN_CLANG_STATIC_ANALYZER=NO"}

    # A whitespace-separated list of default schemes to build.
    #
    # Individual names can be quoted to avoid word splitting.
    : ${SCHEMES:=Squirrel}

    export XCWORKSPACE
    export XCODEPROJ
    export BOOTSTRAP
    export XCTOOL_OPTIONS
    export SCHEMES
}

##
## Code Signing
##

setup_keychain ()
{
  KEY_CHAIN=build.keychain
  security create-keychain -p travis $KEY_CHAIN

  security default-keychain -s $KEY_CHAIN
  security unlock-keychain -p travis $KEY_CHAIN
  security set-keychain-settings -t 3600 -u $KEY_CHAIN
  security import script/certs.p12 -k build.keychain -P $KEY_PASSWORD -T /usr/bin/codesign
}

##
## Build Process
##

main ()
{
    config
    setup_keychain

    if [ -f "$BOOTSTRAP" ]
    then
        echo "*** Bootstrapping..."
        "$BOOTSTRAP" || exit $?
    fi

    echo "*** The following schemes will be built:"
    echo "$SCHEMES" | xargs -n 1 echo "  "
    echo

    echo "$SCHEMES" | xargs -n 1 | (
        local status=0

        while read scheme
        do
            build_scheme "$scheme" || status=1
        done

        exit $status
    )
}

find_pattern ()
{
    ls -d $1 2>/dev/null | head -n 1
}

parse_build ()
{
    awk -f "$SCRIPT_DIR/xctool.awk" 2>&1 >/dev/null
}

build_scheme ()
{
    echo "*** Cleaning Squirrel..."
    xcodebuild -scheme Squirrel -workspace Squirrel.xcworkspace clean >/dev/null || exit $?

    echo "*** Building Squirrel..."
    echo

    xcodebuild -scheme Squirrel -workspace Squirrel.xcworkspace build >/dev/null || exit $?
}

export -f build_scheme
export -f parse_build

main
