#!/usr/bin/env bash
cd "${BASH_SOURCE%/*}"
source ./bashlib
cd ..
export PATH+=:/usr/libexec

addPlistWithKey() {
    local key=$1 type=$2 value=$3 plist=${4:-"$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH"}
    
    PlistBuddy -c "Delete :'$key'" "$plist" 2>/dev/null || true
    PlistBuddy -c "Add :'$key' '$type' '$value'" "$plist"
}
setPlistWithKey() {
    local key=$1 value=$2 plist=${3:-"$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH"}
    
    PlistBuddy -c "Set :'$key' '$value'" "$plist"
}
getPlistWithKey() {
    local key=$1 plist=${2:-"$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH"}
    
    PlistBuddy -c "Print :'$key'" "$plist"
}
setSettingWithTitle() {
    local i title=$1 value=$2 plist=${3:-"$BUILT_PRODUCTS_DIR/$CONTENTS_FOLDER_PATH/Settings.bundle/Root.plist"}
    
    for (( i=0; 1; ++i )); do
        PlistBuddy -c "Print :PreferenceSpecifiers:$i" "$plist" &>/dev/null || break
        inf "Checking preference specifier $i"
    
        [[ $(PlistBuddy -c "Print :PreferenceSpecifiers:$i:Title" "$plist" 2>/dev/null) = $title ]] || continue
    
        inf "Correct title, setting value."
        PlistBuddy -c "Set :PreferenceSpecifiers:$i:DefaultValue $value" "$plist"
        break
    done
}

case $PLATFORM_NAME in
    macosx) platform=mac ;;
    iphone*)    platform=ios ;;
    *)      ftl 'ERROR: Unknown platform: %s.' "$PLATFORM_NAME"; exit 1 ;;
esac

description=$(git describe --always --dirty --long --match "*-$platform*")
version=${description%-g*} build=${version##*-} version=${version%-$build}
version=${version//-$platform/} version=${version//-/.} commit=${description##*-g}

addPlistWithKey GITDescription string "$description"
setPlistWithKey CFBundleVersion "$(hr "${version%%.*}" 14).${version#*.}"
setPlistWithKey CFBundleShortVersionString "$version"

setSettingWithTitle "Build" "$commit"
setSettingWithTitle "Version" "$version"
setSettingWithTitle "Copyright" "$(getPlistWithKey NSHumanReadableCopyright)"

if [[ $DEPLOYMENT_LOCATION = YES ]]; then
    # This build is a release.  Do some release checks.
    fabricPlist="$BUILT_PRODUCTS_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/Fabric.plist"
    passed=1
    [[ $description != *-dirty ]] || \
        { passed=0; err 'ERROR: Cannot release a dirty version, first commit any changes.'; }
    [[ $build == 0 ]] || \
        { passed=0; err 'ERROR: Commit is not tagged for release, first tag accordingly.'; }
    [[ -r "$fabricPlist" && $(PlistBuddy -c "Print :'API Key'" "$fabricPlist" 2>/dev/null) ]] || \
        { passed=0; err 'ERROR: Cannot release: Fabric API key is missing.'; }
    (( passed )) || \
        { ftl "Failed to pass release checks.  Fix the above errors and re-try.  Aborting."; exit 1; }
fi