#!/bin/sh
#
# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
#
# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
# copy, modify, and distribute this software in source code or binary form for use
# in connection with the web services and APIs provided by Facebook.
#
# As with any software that integrates with the Facebook platform, your use of
# this software is subject to the Facebook Developer Principles and Policies
# [http://developers.facebook.com/policy/]. This copyright notice shall be
# included in all copies or substantial portions of the software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN

# shellcheck disable=SC2039

cd "$( dirname "${BASH_SOURCE[0]}" )/.." || exit 1
PROJECT_ROOT=$(pwd)

export SCRIPTS_DIR="$PROJECT_ROOT/scripts"

CORE_ROOT=$PROJECT_ROOT/Facebook.Unity

UNITY_PACKAGE_ROOT=$PROJECT_ROOT/UnitySDK
UNITY_PACKAGE_PLUGIN=$UNITY_PACKAGE_ROOT/Assets/FacebookSDK/Plugins/
export UNITY_ANDROID_PLUGIN=$UNITY_PACKAGE_PLUGIN/Android/
export UNITY_CANVAS_PLUGIN=$UNITY_PACKAGE_PLUGIN/Canvas/
export UNITY_EDITOR_PLUGIN=$UNITY_PACKAGE_PLUGIN/Editor/
export UNITY_IOS_PLUGIN=$UNITY_PACKAGE_PLUGIN/iOS/
export UNITY_SETTINGS_PLUGIN=$UNITY_PACKAGE_PLUGIN/Settings/
export UNITY_WINDOWS_PLUGIN=$UNITY_PACKAGE_PLUGIN/Windows/

RED='\033[0;31m'
NC='\033[0m'
CYAN='\033[0;36m'

# Extract the SDK version from FacebookSdkVersion.java
SDK_VERSION_RAW=$(sed -n 's/.*"\(.*\)\";/\1/p' "$CORE_ROOT/FacebookSdkVersion.cs")
SDK_VERSION_MAJOR=$(echo "$SDK_VERSION_RAW" | awk -F'.' '{print $1}')
SDK_VERSION_MAJOR=${SDK_VERSION_MAJOR:-0}
SDK_VERSION_MINOR=$(echo "$SDK_VERSION_RAW" | awk -F'.' '{print $2}')
SDK_VERSION_MINOR=${SDK_VERSION_MINOR:-0}
SDK_VERSION_REVISION=$(echo "$SDK_VERSION_RAW" | awk -F'.' '{print $3}' | tr -d '\r')
# SDK_VERSION_REVISION=${SDK_VERSION_REVISION:-0}
export SDK_VERSION=$SDK_VERSION_MAJOR.$SDK_VERSION_MINOR.$SDK_VERSION_REVISION

UNITY_JAR_RESOLVER_NAME='unity-jar-resolver'
UNITY_JAR_RESOLVER_PACKAGE_NAME='external-dependency-manager'
UNITY_JAR_RESOLVER_BASE_URL="https://github.com/googlesamples/$UNITY_JAR_RESOLVER_NAME/archive/v"
UNITY_JAR_RESOLVER_VERSION='1.2.166'
UNITY_JAR_RESOLVER_ZIP_URL="$UNITY_JAR_RESOLVER_BASE_URL$UNITY_JAR_RESOLVER_VERSION.zip"

export OUT="$PROJECT_ROOT/out"

# Read UnityReferences.xml and extract unity executable path
set_unity_path_from_settings() {
  UNITY_VERSION_ARRAY=($(awk "/\<UNITY_VERSION\>/, /\<\/UNITY_VERSION\>/" UnityReferences.xml | sed -e "s/\<UNITY_VERSION\>\(.*\)\<\/UNITY_VERSION\>/\1/" | xargs))
  UNITY_VERSION="${UNITY_VERSION_ARRAY[0]}"
  if [ "$UNITY_VERSION" == 'NONE' ]; then
    echo "!Unity project not configured. Please, execute ./configure.sh to set Unity version."
    exit 1
  fi
  UNITY_CONFIG=$(sed -n "/\<PropertyGroup Condition=\"\'\$(UNITY_VERSION)\' == \'$UNITY_VERSION\'\"\>/,/<\/PropertyGroup>/p" UnityReferences.xml | grep -v PropertyGroup)
  MANAGED=($(awk "/\<UNITY_MANAGED_DIR\>/, /\<\/UNITY_MANAGED_DIR\>/" <<< "$UNITY_CONFIG" | sed -e "s/\<UNITY_MANAGED_DIR\>\(.*\)\<\/UNITY_MANAGED_DIR\>/\1/" | xargs))
  UNITY_PATH=$(sed "s/Managed\//MacOS\/Unity/" <<< "${MANAGED[0]}")
  if [ ! -f "$UNITY_PATH" ]; then
      echo "Unity executable $UNITY_PATH not found."
      exit 1
  fi
  echo "Using Unity executable $UNITY_PATH "
}

set_unity_path_from_settings

die() {
  echo ""
  echo "${RED}FATAL: $* ${NC}" >&2
  exit 1
}

# Echoes a progress message to stderr
progress_message() {
    echo "$@" >&2
}

info() {
  echo "${CYAN}$* ${NC}" >&2
}

downloadUnityJarResolverFromGithub() {
  UNITY_JAR_RESOLVER_PACKAGE="$UNITY_JAR_RESOLVER_PACKAGE_NAME.unitypackage"

  pushd "$PROJECT_ROOT" > /dev/null || exit 1
  info "Downloading unity-jar-resolver..."
  curl -L "$UNITY_JAR_RESOLVER_ZIP_URL" > $UNITY_JAR_RESOLVER_NAME.zip || die "Failed to download $UNITY_JAR_RESOLVER_URL"
  unzip -o -j -q $UNITY_JAR_RESOLVER_NAME.zip -d $UNITY_JAR_RESOLVER_NAME
  mv $UNITY_JAR_RESOLVER_NAME/$UNITY_JAR_RESOLVER_PACKAGE_NAME-$UNITY_JAR_RESOLVER_VERSION.unitypackage "$PROJECT_ROOT"/$UNITY_JAR_RESOLVER_PACKAGE
  rm -rf $UNITY_JAR_RESOLVER_NAME.zip $UNITY_JAR_RESOLVER_NAME
  info "Importing unity-jar-resolver to UnitySDK project..."

  UNITY_PACKAGE_PATH="$PROJECT_ROOT/$UNITY_JAR_RESOLVER_PACKAGE"

  $UNITY_PATH -quit -batchmode -logFile -nographics -projectPath="$PROJECT_ROOT/UnitySDK" \
   -importPackage "$UNITY_PACKAGE_PATH" || die "Failed to import $UNITY_PACKAGE_PATH"
  info "Cleaning up..."
  rm "$UNITY_PACKAGE_PATH"
  popd > /dev/null || exit 1
}

validate_file_exists() {
  if [ ! -f "$1" ]; then
    echo "${RED}FATAL: File not found $1 ${NC}" >&2
    die "$2"
  fi
}

validate_any_file_exists() {
  FILE_COUNT=$(find "$1" -name "$2" | wc -l)

  if [[ $FILE_COUNT -eq 0 ]]; then
    echo "${RED}FATAL: File not found $2 ${NC}" >&2
    die "$3"
  fi
}


#!/bin/sh
#
# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
#
# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
# copy, modify, and distribute this software in source code or binary form for use
# in connection with the web services and APIs provided by Facebook.
#
# As with any software that integrates with the Facebook platform, your use of
# this software is subject to the Facebook Developer Principles and Policies
# [http://developers.facebook.com/policy/]. This copyright notice shall be
# included in all copies or substantial portions of the software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN

# This file performs the custom build logic to setup the Plugins
# in the unity project

# shellcheck disable=SC2039

. "$(dirname "$0")/common.sh"

UNITY_CSPROJ=$UNITY_PACKAGE_ROOT/Assets/ExternalDependencyManager/Editor

fix_meta(){
  cp "$1" "$UNITY_CSPROJ/meta.txt"
  sed s/_v1.2.166././g "$UNITY_CSPROJ/meta.txt" > "$1"
  rm "$UNITY_CSPROJ/meta.txt"
}

set_name(){
  if [ ! -f "$1" ]; then
    echo "Missing DLL"
    echo "$1"
    exit 1
  fi
  mv "$1" "$2"
  mv "$1.meta" "$2.meta"
  fix_meta "$2.meta"
}

set_name $UNITY_CSPROJ/Google.IOSResolver*.dll "$UNITY_CSPROJ/Google.IOSResolver.dll"
set_name $UNITY_CSPROJ/Google.IOSResolver*.dll.mdb "$UNITY_CSPROJ/Google.IOSResolver.dll.mdb"
set_name $UNITY_CSPROJ/Google.JarResolver*.dll "$UNITY_CSPROJ/Google.JarResolver.dll"
set_name $UNITY_CSPROJ/Google.JarResolver*.dll.mdb "$UNITY_CSPROJ/Google.JarResolver.dll.mdb"
set_name $UNITY_CSPROJ/Google.PackageManagerResolver*.dll "$UNITY_CSPROJ/Google.PackageManagerResolver.dll"
set_name $UNITY_CSPROJ/Google.PackageManagerResolver*.dll.mdb "$UNITY_CSPROJ/Google.PackageManagerResolver.dll.mdb"
set_name $UNITY_CSPROJ/Google.VersionHandlerImpl*.dll "$UNITY_CSPROJ/Google.VersionHandlerImpl.dll"
set_name $UNITY_CSPROJ/Google.VersionHandlerImpl*.dll.mdb "$UNITY_CSPROJ/Google.VersionHandlerImpl.dll.mdb"

cp "$UNITY_CSPROJ/external-dependency-manager_version-1.2.166_manifest.txt" $UNITY_CSPROJ/tmp.txt
## TO DO: obtain the dependency version dinamically
sed s/_v1.2.166././g "$UNITY_CSPROJ/tmp.txt" > "$UNITY_CSPROJ/external-dependency-manager_version-1.2.166_manifest.txt"
rm "$UNITY_CSPROJ/tmp.txt"

mkdir -p "$UNITY_CSPROJ/1.2.166/"
mv "$UNITY_CSPROJ/Google.IOSResolver.dll" "$UNITY_CSPROJ/1.2.166/Google.IOSResolver.dll"
mv "$UNITY_CSPROJ/Google.IOSResolver.dll.mdb" "$UNITY_CSPROJ/1.2.166/Google.IOSResolver.dll.mdb"
mv "$UNITY_CSPROJ/Google.JarResolver.dll" "$UNITY_CSPROJ/1.2.166/Google.JarResolver.dll"
mv "$UNITY_CSPROJ/Google.JarResolver.dll.mdb" "$UNITY_CSPROJ/1.2.166/Google.JarResolver.dll.mdb"
mv "$UNITY_CSPROJ/Google.PackageManagerResolver.dll" "$UNITY_CSPROJ/1.2.166/Google.PackageManagerResolver.dll"
mv "$UNITY_CSPROJ/Google.PackageManagerResolver.dll.mdb" "$UNITY_CSPROJ/1.2.166/Google.PackageManagerResolver.dll.mdb"
mv "$UNITY_CSPROJ/Google.VersionHandlerImpl.dll" "$UNITY_CSPROJ/1.2.166/Google.VersionHandlerImpl.dll"
mv "$UNITY_CSPROJ/Google.VersionHandlerImpl.dll.mdb" "$UNITY_CSPROJ/1.2.166/Google.VersionHandlerImpl.dll.mdb"


#!/bin/sh
#
# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
#
# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
# copy, modify, and distribute this software in source code or binary form for use
# in connection with the web services and APIs provided by Facebook.
#
# As with any software that integrates with the Facebook platform, your use of
# this software is subject to the Facebook Developer Principles and Policies
# [http://developers.facebook.com/policy/]. This copyright notice shall be
# included in all copies or substantial portions of the software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN

# This file performs the custom build logic to setup the Plugins
# in the unity project

. $(dirname $0)/common.sh

$UNITY_PATH -batchmode -nographics -projectPath "$UNITY_PACKAGE_ROOT" -executeMethod FacebookConsoleEndpoint.ExportPackage -quit \
|| die "Failed to export package. Make sure the Facebook.Unity project is not open in Unity"

info "Unity Package exported to $PROJECT_ROOT/out/facebook-unity-sdk-$SDK_VERSION.unitypackage"


#!/bin/sh
# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
#
# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
# copy, modify, and distribute this software in source code or binary form for use
# in connection with the web services and APIs provided by Facebook.
#
# As with any software that integrates with the Facebook platform, your use of
# this software is subject to the Facebook Developer Principles and Policies
# [http://developers.facebook.com/policy/]. This copyright notice shall be
# included in all copies or substantial portions of the software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# shellcheck disable=SC2039

set -euo pipefail

# --------------
# Functions
# --------------

# Main
main() {
  SDK_SCRIPTS_DIR=$(realpath "$(dirname "${BASH_SOURCE[0]}")")
  SDK_DIR="$(dirname "$SDK_SCRIPTS_DIR")"

  SDK_VERSION_FILES=(
    "scripts/build.properties"
    "Facebook.Unity/FacebookSdkVersion.cs"
    "Facebook.Unity/Properties/AssemblyInfo.cs"
    "Facebook.Unity.Canvas/Properties/AssemblyInfo.cs"
    "Facebook.Unity.Editor/Properties/AssemblyInfo.cs"
    "Facebook.Unity.IOS/Properties/AssemblyInfo.cs"
    "Facebook.Unity.IOS.StrippingHack/Properties/AssemblyInfo.cs"
    "Facebook.Unity.Android/Properties/AssemblyInfo.cs"
    "Facebook.Unity.Android.StrippingHack/Properties/AssemblyInfo.cs"
    "Facebook.Unity.Settings/Properties/AssemblyInfo.cs"
    "Facebook.Unity.Tests/Properties/AssemblyInfo.cs"
  )

  SDK_MAIN_VERSION_FILE="scripts/build.properties"
  SDK_CURRENT_VERSION=$(grep -Eo "UNITY_SDK_BUILD_VERSION='.*'" "$SDK_MAIN_VERSION_FILE" | awk -F "'" '{print $2}')

  SDK_GIT_REMOTE="https://github.com/facebook/facebook-sdk-for-unity"

  local command_type=${1:-}
  if [ -n "$command_type" ]; then shift; fi

  case "$command_type" in
  "bump-changelog") bump_changelog "$@" ;;
  "bump-version") bump_version "$@" ;;
  "tag-current-version") tag_current_version "$@" ;;
  "--help" | "help") echo "Check main() for supported commands" ;;
  esac
}

# Bump Changelog
bump_changelog() {
  local new_version=${1:-}

  # Edit Changelog
  updated_changelog=""

  while IFS= read -r line; do
    if [[ $line == "## [Unreleased]"* ]]; then
      current_date=$(date +%Y-%m-%d)
      updated_line=$line"\n"
      updated_line=$updated_line"\n"
      updated_line=$updated_line"## [$new_version] - $current_date\n"
    elif [[ $line == "[Unreleased]"* ]]; then
      updated_line="[Unreleased]: $SDK_GIT_REMOTE/compare/sdk-version-$new_version...HEAD\n"
      updated_line=$updated_line"[$new_version]: $SDK_GIT_REMOTE/compare/sdk-version-$SDK_CURRENT_VERSION...sdk-version-$new_version\n"
    else
      updated_line=$line"\n"
    fi
    updated_changelog=$updated_changelog$updated_line
  done <"CHANGELOG.md"

  echo "$updated_changelog" >CHANGELOG.md
}

# Bump Version
bump_version() {
  local new_version=${1:-}

  if [ "$new_version" == "$SDK_CURRENT_VERSION" ]; then
    echo "This version is the same as the current version"
    false
    return
  fi

  if ! is_valid_semver "$new_version"; then
    echo "This version isn't a valid semantic versioning"
    false
    return
  fi

  echo "Changing from: $SDK_CURRENT_VERSION to: $new_version"

  # Replace the previous version to the new version in relative files
  for file_path in "${SDK_VERSION_FILES[@]}"; do
    local full_file_path="$SDK_DIR/$file_path"

    if [ ! -f "$full_file_path" ]; then
      echo "*** NOTE: unable to find $full_file_path."
      continue
    fi

    local temp_file="$full_file_path.tmp"
    sed -e "s/$SDK_CURRENT_VERSION/$new_version/g" "$full_file_path" >"$temp_file"
    if diff "$full_file_path" "$temp_file" >/dev/null; then
      echo "*** ERROR: unable to update $full_file_path"
      rm "$temp_file"
      continue
    fi

    mv "$temp_file" "$full_file_path"
  done

  bump_changelog "$new_version"
}

# Tag push current version
tag_current_version() {
  if ! is_valid_semver "$SDK_CURRENT_VERSION"; then
    exit 1
  fi

  if does_version_exist "$SDK_CURRENT_VERSION"; then
    echo "Version $SDK_CURRENT_VERSION already exists"
    false
    return
  fi

  git tag -a "sdk-version-$SDK_CURRENT_VERSION" -m "Version $SDK_CURRENT_VERSION"

  if [ "${1:-}" == "--push" ]; then
    git push origin "sdk-version-$SDK_CURRENT_VERSION"
  fi
}

# Proper Semantic Version
is_valid_semver() {
  if ! [[ ${1:-} =~ ^([0-9]{1}|[1-9][0-9]+)\.([0-9]{1}|[1-9][0-9]+)\.([0-9]{1}|[1-9][0-9]+)($|[-+][0-9A-Za-z+.-]+$) ]]; then
    false
    return
  fi
}

# Check Version Tag Exists
does_version_exist() {
  local version_to_check=${1:-}

  if [ "$version_to_check" == "" ]; then
    version_to_check=$SDK_CURRENT_VERSION
  fi

  if [ ! -d "$SDK_DIR"/.git ]; then
    echo "Not a Git Repository"
    return
  fi

  if git rev-parse "v$version_to_check" >/dev/null 2>&1; then
    return
  fi

  if git rev-parse "sdk-version-$version_to_check" >/dev/null 2>&1; then
    return
  fi

  false
}

# --------------
# Main Script
# --------------

main "$@"


#!/bin/sh
#
# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
#
# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
# copy, modify, and distribute this software in source code or binary form for use
# in connection with the web services and APIs provided by Facebook.
#
# As with any software that integrates with the Facebook platform, your use of
# this software is subject to the Facebook Developer Principles and Policies
# [http://developers.facebook.com/policy/]. This copyright notice shall be
# included in all copies or substantial portions of the software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN

# This file performs the custom build logic to setup the Plugins
# in the unity project

. "$(dirname "$0")/common.sh"

# Run build script to ensure that test DLL is built
"$SCRIPTS_DIR/build.sh" || die "Build failed"

command -v mono >/dev/null 2>&1 || die "mono command not found. Please install mono."

NSUBSTITUTE_CONSOLE="$PROJECT_ROOT/packages/NSubstitute.2.0.3/lib"
NUNIT_CONSOLE="$PROJECT_ROOT/packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe"
TEST_DLL="$PROJECT_ROOT/Facebook.Unity.Tests/bin/Release/Facebook.Unity.Tests.dll"

validate_any_file_exists "$NSUBSTITUTE_CONSOLE" "NSubstitute.dll" "Make sure NSubstitute is installed at /packages"
validate_file_exists "$NUNIT_CONSOLE" "Make sure mono is installed at this path"
validate_file_exists "$TEST_DLL" "Make sure that the Unity Project successfully built"

mono "$NUNIT_CONSOLE" "$TEST_DLL" --workers=0 || die "Some tests failed"


#!/bin/sh
#
# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
#
# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
# copy, modify, and distribute this software in source code or binary form for use
# in connection with the web services and APIs provided by Facebook.
#
# As with any software that integrates with the Facebook platform, your use of
# this software is subject to the Facebook Developer Principles and Policies
# [http://developers.facebook.com/policy/]. This copyright notice shall be
# included in all copies or substantial portions of the software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN

# This file performs the custom build logic to setup the Plugins
# in the unity project

# shellcheck disable=SC2039

. "$(dirname "$0")/common.sh"

command -v nuget >/dev/null 2>&1 || die "nuget command not found. Please install nuget."
echo "checking packages..."
nuget restore "$PROJECT_ROOT"
echo "checking packages done."

#skycatle build
skycastleBuild=false
if [[ $* != *--skycastle* ]]; then
cd "$SCRIPTS_DIR" || die "$SCRIPTS_DIR not found"
./build.sh
fi

"$SCRIPTS_DIR/setup_ios_unity_plugin.sh" "$@" || die "Failed to setup the ios sdk plugin"
"$SCRIPTS_DIR/setup_android_unity_plugin.sh" "$@" || die "Failed to build the android sdk plugin"

cd "$SCRIPTS_DIR" || die "$SCRIPTS_DIR not found"
./build.sh


#!/bin/sh
#
# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
#
# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
# copy, modify, and distribute this software in source code or binary form for use
# in connection with the web services and APIs provided by Facebook.
#
# As with any software that integrates with the Facebook platform, your use of
# this software is subject to the Facebook Developer Principles and Policies
# [http://developers.facebook.com/policy/]. This copyright notice shall be
# included in all copies or substantial portions of the software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN

# shellcheck disable=SC2039

. $(dirname $0)/common.sh

source "$PROJECT_ROOT/scripts/build.properties"

info "Starting build"
# Check for required settings
if [ -z "$ANDROID_HOME" ]; then
    echo "${RED}ERROR: ANDROID_HOME environment variable not set${NC}"
    echo "${RED}Please set the ANDROID_HOME environment variable to point to your android sdk${NC}"
    exit 1
fi

localBuild=false
if [[ $* == *--local* ]]; then
  localBuild=true
fi

#skycatle build
skycastleBuild=false
if [[ $* == *--skycastle* ]]; then
  skycastleBuild=true
fi

# Copy the required libs
UNITY_PLUGIN_FACEBOOK="$UNITY_PACKAGE_ROOT/Assets/FacebookSDK/Plugins/Android/libs"

FB_WRAPPER_PATH="$PROJECT_ROOT/facebook-android-wrapper"
FB_ANDROID_SDK_WRAPPER_NAME="facebook-android-wrapper.aar"
FB_ANDROID_SDK_WRAPPER="$FB_WRAPPER_PATH/build/outputs/aar/$FB_ANDROID_SDK_WRAPPER_NAME"

# Local build only properties
FB_WRAPPER_LIB_PATH="$FB_WRAPPER_PATH/libs"
FB_GS_SDK_AAR_NAME="facebook-gamingservices-release.aar"
# FB_GS_SDK_AAR_PATH="$FB_WRAPPER_LIB_PATH/$FB_GS_SDK_AAR_NAME"
FB_GS_SDK_AAR="$FB_ANDROID_SDK_PATH/facebook-gamingservices/build/outputs/aar/$FB_GS_SDK_AAR_NAME"

# Get Unity Jar Resolver
info "Step 1 - Download $UNITY_JAR_RESOLVER_NAME"
if [ "$skycastleBuild" = true ]; then
  info "Using custom version from Skycastle builder resource repo."
else
  downloadUnityJarResolverFromGithub
fi

info "Step 2 - Build android wrapper"
pushd "$FB_WRAPPER_PATH"
if [ "$localBuild" = true ]; then
  if [ ! -d "$FB_WRAPPER_LIB_PATH" ]; then
    mkdir -p "$FB_WRAPPER_LIB_PATH" || die "Failed to create wrapper libs folder"
  fi
  info "Step 2.1 - Build local Facebook Gaming Services Android SDK at '$FB_ANDROID_SDK_PATH'"
  pushd $FB_ANDROID_SDK_PATH
  ./gradlew :facebook-gamingservices:assemble || die "Failed to build Facebook Gaming Services Android SDK"
  popd
  info "Step 2.2 - Copy $FB_ANDROID_SDK_AAR to $FB_WRAPPER_LIB_PATH/$FB_GS_SDK_AAR_NAME folder"
  cp "$FB_GS_SDK_AAR" "$FB_WRAPPER_LIB_PATH/$FB_GS_SDK_AAR_NAME" || die "Failed to copy sdk to wrapper libs folder"
  ./gradlew clean -PlocalRepo=libs -PsdkVersion="$FB_ANDROID_SDK_VERSION" -Pskycastle=$skycastleBuild || die "Failed to perform gradle clean"
  ./gradlew assemble -PlocalRepo=libs -PsdkVersion="$FB_ANDROID_SDK_VERSION" -Pskycastle=$skycastleBuild || die "Failed to build facebook android wrapper"
else
  ./gradlew clean -Pskycastle=$skycastleBuild || die "Failed to perform gradle clean"
  ./gradlew assemble -Pskycastle=$skycastleBuild || die "Failed to build facebook android wrapper"
fi
popd

info "Step 3 - Copy libs to unity plugin folder"
if [ ! -d "$UNITY_PLUGIN_FACEBOOK" ]; then
  mkdir -p "$UNITY_PLUGIN_FACEBOOK" || die "Failed to make unity plugin lib folder"
fi
# clean the unity lib folder
rm -rf $UNITY_PLUGIN_FACEBOOK/*.jar
rm -rf $UNITY_PLUGIN_FACEBOOK/*.aar
rm -rf $UNITY_PLUGIN_FACEBOOK/*.meta

# Copy aars
cp "$FB_ANDROID_SDK_WRAPPER" "$UNITY_PLUGIN_FACEBOOK" || die 'Failed to copy wrapper to unity plugin folder'
# Rename wrapper to include sdk version
mv "$UNITY_PLUGIN_FACEBOOK/$FB_ANDROID_SDK_WRAPPER_NAME" "$UNITY_PLUGIN_FACEBOOK/facebook-android-wrapper-$SDK_VERSION.aar"

info "Done!"


#!/bin/sh
#
# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
#
# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
# copy, modify, and distribute this software in source code or binary form for use
# in connection with the web services and APIs provided by Facebook.
#
# As with any software that integrates with the Facebook platform, your use of
# this software is subject to the Facebook Developer Principles and Policies
# [http://developers.facebook.com/policy/]. This copyright notice shall be
# included in all copies or substantial portions of the software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN

# shellcheck disable=SC2039

. "$(dirname "$0")/common.sh"

cd "$(dirname "$0")/.." || die "$(dirname "$0")/.. not found"
PROJECT_ROOT=$(pwd)
. "$PROJECT_ROOT/scripts/build.properties"

rm -rf tempIosBuild
mkdir tempIosBuild
cd tempIosBuild || die "Directory tempIosBuild not found"

UNITY_PLUGIN_FACEBOOK="$UNITY_PACKAGE_ROOT/Assets/FacebookSDK/Plugins/iOS"
mkdir -p "$UNITY_PLUGIN_FACEBOOK"
rm -rf "$UNITY_PLUGIN_FACEBOOK/*.framework"

cd "$PROJECT_ROOT" || die "$PROJECT_ROOT not found"
rm -rf tempIosBuild


#!/bin/sh
# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
#
# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
# copy, modify, and distribute this software in source code or binary form for use
# in connection with the web services and APIs provided by Facebook.
#
# As with any software that integrates with the Facebook platform, your use of
# this software is subject to the Facebook Developer Principles and Policies
# [http://developers.facebook.com/policy/]. This copyright notice shall be
# included in all copies or substantial portions of the software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# shellcheck disable=SC2039

# --------------
# Main Script
# --------------

CACHE="$(pwd)/cache"
LOGFILE="$(pwd)/tmp.log"

OSX_DOTNET_PACKAGE_URL="https://download.visualstudio.microsoft.com/download/pr/5c281f95-91c4-499d-baa2-31fec919047a/38c6964d72438ac30032bce516b655d9/dotnet-sdk-3.0.100-osx-x64.pkg"
OSX_UNITY_PACKAGE_URL="https://download.unity3d.com/download_unity/e80cc3114ac1/MacEditorInstaller/Unity-5.6.7f1.pkg"

install() {
  # Download Unity Package from URL if it doesn't exist in cache directory
  local url=${1:-}
  local filename=$(basename $url)

  if [ ! -f "$CACHE/$filename" ]; then
    echo "*** NOTE: unable to find $filename, download from $url."
    mkdir -p "$CACHE"
    curl -o "$CACHE/$filename" "$url"
  fi

  # Install Unity Package
  sudo installer -dumplog -package "$CACHE/$filename" -target /
}

brew tap caskroom/cask
brew cask install android-sdk  > "$LOGFILE"
brew install gradle  > "$LOGFILE"

echo yes | $ANDROID_HOME/tools/bin/sdkmanager "platforms;android-27" "build-tools;27.0.3" > "$LOGFILE"

install $OSX_DOTNET_PACKAGE_URL
install $OSX_UNITY_PACKAGE_URL


# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

# We must use the full path to aws, since non-interactive shells do not source ~/.bashrc
aws configure set aws_access_key_id $1
aws configure set aws_secret_access_key $2
aws configure set default.region $3

KOPS_STATE_BUCKET=$6-facebook360-dep-kops-state-store
export KOPS_CLUSTER_NAME=$6.facebook360.dep.k8s.local
export KOPS_STATE_STORE=s3://${KOPS_STATE_BUCKET}

aws s3api create-bucket --bucket ${KOPS_STATE_BUCKET} --region us-west-2 --create-bucket-configuration LocationConstraint=us-west-2 &> /dev/null
aws s3api put-bucket-versioning --bucket ${KOPS_STATE_BUCKET} --versioning-configuration Status=Enabled

kops create secret --name ${KOPS_CLUSTER_NAME} sshpublickey admin -i ~/.ssh/id_rsa.pub

if $7; then
  echo "Deleting old cluster. This can take a few minutes..."
  kops delete cluster --yes
fi

kops create cluster \
  --node-count=$4 \
  --master-size=c4.large \
  --node-size=$5 \
  --zones=us-west-2a \
  --image kope.io/k8s-1.12-debian-stretch-amd64-hvm-ebs-2019-05-13 \
  --kubernetes-version 1.12.0 &> /dev/null

# Enable Kops Installation Hook and DevicePlugins for Nvidia GPUs
if [[ $5 == p* ]] || [[ $5 == g* ]]; then
  kops get ig nodes -o yaml > scripts/aws/ig.yml
  echo "  hooks:" >> scripts/aws/ig.yml
  echo "  - execContainer:" >> scripts/aws/ig.yml
  echo "      image: dcwangmit01/nvidia-device-plugin:0.1.0" >> scripts/aws/ig.yml
  kops replace -f scripts/aws/ig.yml
fi

kops update cluster --name ${KOPS_CLUSTER_NAME} --yes &> /dev/null

echo "Spawning $(($4 + 1)) machines. This can take several minutes..."
while [ 1 ]
do
    kops validate cluster && break || (sleep 1 && echo -e "\nStill initializing...\n" && sleep 10)
done

# Deploy the Daemonset for the Nvidia DevicePlugin
if [[ $5 == p* ]] || [[ $5 == g* ]]; then
  error_msg=$(kubectl create -f https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/v1.12/nvidia-device-plugin.yml 2>1&)
  if [[ ${error_msg} == *AlreadyExists*  ]]; then
    exit 0
  fi
fi


# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

# Flushes the queue from any previous (incomplete) runs
sudo service rabbitmq-server restart

# Allows access to AWS secretes
if [ $(kubectl get secrets | grep aws-storage-key | wc -l) > 0 ]; then
  kubectl delete secrets aws-storage-key
fi

kubectl create secret generic aws-storage-key \
  --from-literal=AWS_ACCESS_KEY_ID=$(aws configure get aws_access_key_id) \
  --from-literal=AWS_SECRET_ACCESS_KEY=$(aws configure get aws_secret_access_key)

# Get k8s cluster ready
sed "s|<REPO_NAME>|$1:worker|g" scripts/aws/farm.yml.template > scripts/aws/farm.yml
sed -i "s|<MASTER_IP>|$2|g" scripts/aws/farm.yml
sed -i "s|<WORKER_COUNT>|$3|g" scripts/aws/farm.yml
kubectl apply -f scripts/aws/farm.yml

# Ensure that all the pods receive the newest image
kubectl delete pods --all --grace-period=0 --force


# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

if hash nvidia-docker 2>/dev/null; then
  echo "Found nvidia-docker"
else
  # Check if we have an NVIDIA GPU
  sudo apt-get install -y mesa-utils
  if glxinfo | grep -i "nvidia"; then
    echo "Installing nvidia drivers. It make take a few minutes..."
    sudo apt-get update
    sudo apt install -y build-essential gcc libc-dev
    sudo apt-get install -y linux-headers-$(uname -r)
    wget https://developer.nvidia.com/compute/cuda/10.1/Prod/local_installers/cuda_10.1.168_418.67_linux.run
    sudo sh cuda_10.1.168_418.67_linux.run --silent --driver --toolkit

    # Display GPU info
    nvidia-smi

    echo "Installing nvidia-docker..."

    # Add the package repositories
    curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -
    distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
    curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list
    sudo apt-get update

    # Install nvidia-docker2 and reload the Docker daemon configuration
    sudo apt-get install -y nvidia-docker2
    sudo pkill -SIGHUP dockerd

    # To test nvidia-smi with the latest official CUDA image
    # sudo docker run --runtime=nvidia --rm nvidia/cuda:9.0-base nvidia-smi
  else
    echo "No NVIDIA GPU found. Skipping GPU setup..."
  fi
fi


#!/bin/bash

set -ex

export MAX_JOBS=1

# install python
apt-get update
apt-get -y install python python-pip git-core

pip install virtualenv

# setup virtualenv
VENV_DIR=/tmp/venv
PYTHON="$(which python)"
if [[ "${CIRCLE_JOB}" =~ py((2|3)\\.?[0-9]?\\.?[0-9]?) ]]; then
    PYTHON=$(which "python${BASH_REMATCH[1]}")
fi
$PYTHON -m virtualenv "$VENV_DIR"
source "$VENV_DIR/bin/activate"
pip install -U pip setuptools

# define some variables
FAI_PEP_DIR=/tmp/FAI-PEP
CONFIG_DIR=/tmp/config
LOCAL_REPORTER_DIR=/tmp/reporter

REPO_DIR=/tmp/pytorch

BENCHMARK_FILE=${FAI_PEP_DIR}/specifications/models/caffe2/squeezenet/squeezenet.json

mkdir -p "$CONFIG_DIR"
mkdir -p "$LOCAL_REPORTER_DIR"

# clone FAI-PEP
rm -rf ${FAI_PEP_DIR}
git clone https://github.com/facebook/FAI-PEP.git "$FAI_PEP_DIR"
pip install six requests

# set up default arguments
echo "
{
  \"--commit\": \"master\",
  \"--exec_dir\": \"${CONFIG_DIR}/exec\",
  \"--framework\": \"caffe2\",
  \"--local_reporter\": \"${CONFIG_DIR}/reporter\",
  \"--model_cache\": \"${CONFIG_DIR}/model_cache\",
  \"--platforms\": \"host/incremental\",
  \"--remote_repository\": \"origin\",
  \"--repo\": \"git\",
  \"--repo_dir\": \"${REPO_DIR}\",
  \"--root_model_dir\": \"${CONFIG_DIR}/root_model_dir\",
  \"--screen_reporter\": null
}
" > ${CONFIG_DIR}/config.txt

# clone/install pytorch
pip install numpy pyyaml mkl mkl-include setuptools cmake cffi typing

if [ ! -d "${REPO_DIR}" ]; then
  git clone --recursive --quiet https://github.com/pytorch/pytorch.git "$REPO_DIR"
fi

# install ninja to speedup the build
pip install ninja

# run benchmark
RUN_IMAGENET=0
if [ $# -gt 0 ]; then
  if [ ! -z "$1" ]; then
    RUN_IMAGENET=1
  fi
fi

if [ ${RUN_IMAGENET} -gt 0 ]; then
  # install opencv for image conversion
  if [ ! -d /tmp/opencv-3.4.3 ]; then
    apt-get -y install wget unzip
    wget -O /tmp/opencv.zip https://github.com/opencv/opencv/archive/3.4.3.zip
    unzip -q /tmp/opencv.zip -d /tmp/
    cd /tmp/opencv-3.4.3/
    mkdir build
    cd build
    cmake ..
    make -j 4
    make install
  fi

  python ${FAI_PEP_DIR}/benchmarking/run_bench.py -b ${FAI_PEP_DIR}/specifications/models/caffe2/squeezenet/squeezenet_accuracy_imagenet.json --string_map "{\"imagenet_dir\": \"$1\"}" --config_dir "${CONFIG_DIR}"

else
  python ${FAI_PEP_DIR}/benchmarking/run_bench.py -b "${BENCHMARK_FILE}" --config_dir "${CONFIG_DIR}"
fi


#!/bin/bash

set -ex

export MAX_JOBS=1

# install python
apt-get update
apt-get -y install python python-pip git-core

pip install virtualenv

# setup virtualenv
VENV_DIR=/tmp/venv
PYTHON="$(which python)"
if [[ "${CIRCLE_JOB}" =~ py((2|3)\\.?[0-9]?\\.?[0-9]?) ]]; then
    PYTHON=$(which "python${BASH_REMATCH[1]}")
fi
$PYTHON -m virtualenv "$VENV_DIR"
source "$VENV_DIR/bin/activate"
pip install -U pip setuptools

# define some variables
FAI_PEP_DIR=/tmp/FAI-PEP
CONFIG_DIR=/tmp/config
REPO_DIR=/tmp/tensorflow
LOCAL_REPORTER_DIR=/tmp/reporter

BAZEL_DIR=/tmp/bazel
BAZEL=bazel-0.25.0-installer-linux-x86_64.sh

BENCHMARK_FILE=${FAI_PEP_DIR}/specifications/models/tflite/mobilenet_v2/mobilenet_v2_0.35_96.json

mkdir -p "$CONFIG_DIR"
mkdir -p "$LOCAL_REPORTER_DIR"

# clone FAI-PEP
rm -rf ${FAI_PEP_DIR}
git clone https://github.com/facebook/FAI-PEP.git "$FAI_PEP_DIR"
pip install six requests

# set up default arguments
echo "
{
  \"--commit\": \"master\",
  \"--exec_dir\": \"${CONFIG_DIR}/exec\",
  \"--framework\": \"tflite\",
  \"--local_reporter\": \"${CONFIG_DIR}/reporter\",
  \"--model_cache\": \"${CONFIG_DIR}/model_cache\",
  \"--platforms\": \"host\",
  \"--remote_repository\": \"origin\",
  \"--repo\": \"git\",
  \"--repo_dir\": \"${REPO_DIR}\",
  \"--root_model_dir\": \"${CONFIG_DIR}/root_model_dir\",
  \"--screen_reporter\": null
}
" > ${CONFIG_DIR}/config.txt

# clone/install tflite

apt-get install wget pkg-config g++ zlib1g-dev python zip unzip -y
if [ ! -z ${BAZEL_DIR} ]; then
  mkdir -p ${BAZEL_DIR}
fi
if [ ! -f ${BAZEL_DIR}/${BAZEL} ]; then
  wget -q -O ${BAZEL_DIR}/${BAZEL} https://github.com/bazelbuild/bazel/releases/download/0.25.0/${BAZEL}
fi
chmod +x ${BAZEL_DIR}/${BAZEL}
${BAZEL_DIR}/${BAZEL} --user
export PATH="$PATH:$HOME/bin"

rm -rf ${REPO_DIR}
git clone --recursive --quiet https://github.com/tensorflow/tensorflow.git "$REPO_DIR"

# run benchmark

python ${FAI_PEP_DIR}/benchmarking/run_bench.py -b "${BENCHMARK_FILE}" --config_dir "${CONFIG_DIR}"


#!/bin/sh

rm -rf $1/build/
$1/scripts/build_local.sh -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DUSE_OBSERVERS=ON
cp $1/build/bin/caffe2_benchmark $2


#!/bin/sh

set -ex

rm -rf $1/build*
$1/scripts/build_android.sh -DBUILD_BINARY=ON -DUSE_OBSERVERS=ON -DUSE_ZSTD=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON
cp $1/build_android/bin/caffe2_benchmark $2


#!/bin/sh

set -ex

rm -rf $1/build*
$1/scripts/build_android.sh -DBUILD_BINARY=ON -DUSE_OBSERVERS=ON -DUSE_ZSTD=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DANDROID_TOOLCHAIN=clang
cp $1/build_android/bin/caffe2_benchmark $2


#!/bin/sh

 set -ex

$1/scripts/build_android.sh -DBUILD_BINARY=ON -DUSE_OBSERVERS=ON -DUSE_ZSTD=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON
cp "$1/build_android/bin/caffe2_benchmark" "$2"


#!/bin/sh

set -ex

DIR=$(dirname "$2")

$1/scripts/build_local.sh -DBUILD_SHARED_LIBS=OFF -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DUSE_OBSERVERS=ON -DUSE_OPENCV=ON
$1/scripts/build_android.sh -DBUILD_BINARY=ON -DUSE_OBSERVERS=ON -DUSE_ZSTD=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON
cp "$1/build/bin/convert_image_to_tensor" "${DIR}/convert_image_to_tensor"
cp "$1/build_android/bin/caffe2_benchmark" "$2"


#!/bin/sh

set -ex
DIR=$(dirname "$2")

rm -rf $1/build/
$1/scripts/build_local.sh -DBUILD_SHARED_LIBS=OFF -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DUSE_OBSERVERS=ON -DUSE_OPENCV=ON
cp $1/build/bin/caffe2_benchmark $2
if [ -f $1/build/bin/convert_image_to_tensor ]; then
  cp "$1/build/bin/convert_image_to_tensor" "${DIR}/convert_image_to_tensor"
fi


#!/bin/sh

set -ex

DIR=$(dirname "$2")

$1/scripts/build_local.sh -DBUILD_SHARED_LIBS=OFF -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DUSE_OBSERVERS=ON -DUSE_OPENCV=ON
cp $1/build/bin/caffe2_benchmark $2
if [ -f $1/build/bin/convert_image_to_tensor ]; then
  cp "$1/build/bin/convert_image_to_tensor" "${DIR}/convert_image_to_tensor"
fi


#!/bin/sh

set -ex

rm -rf $1/build/
$1/scripts/build_local.sh -DBUILD_SHARED_LIBS=OFF -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DUSE_OBSERVERS=ON
cp $1/build/bin/caffe2_benchmark $2


#!/bin/sh

set -ex

rm -rf $1/build/
$1/scripts/build_local.sh -DBUILD_SHARED_LIBS=OFF -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DBLAS=MKL -DUSE_OBSERVERS=ON
cp $1/build/bin/caffe2_benchmark $2


#!/bin/sh

set -ex

DIR=${PWD}
# the configure must be run once beforehand
cd "$1"

# build benchmark binary
# assuming the configure has set up the NDK and SDK correctly
bazel build -c opt \
  --config=android_arm \
  --cxxopt='--std=c++11' \
  tensorflow/lite/tools/benchmark:benchmark_model

cd ${DIR}

cp "$1/bazel-bin/tensorflow/lite/tools/benchmark/benchmark_model" "$2"


#!/bin/sh

set -ex

DIR=${PWD}
# the configure must be run once beforehand
cd "$1"

# build benchmark binary
# assuming the configure has set up the NDK and SDK correctly
bazel build -c opt \
  --config=android_arm \
  --cxxopt='--std=c++11' \
  --copt=-DTFLITE_PROFILING_ENABLED \
  tensorflow/lite/tools/benchmark:benchmark_model

cd ${DIR}
cp "$1/bazel-bin/tensorflow/lite/tools/benchmark/benchmark_model" "$2"


#!/bin/sh

set -ex

DIR=${PWD}
# the configure must be run once beforehand
cd "$1"

echo "OS is $(uname)"

LINKER_OPTS=""
if [ "$(uname)" = 'Linux' ]; then
  LINKER_OPTS="--linkopt -latomic"
fi
echo "OPTS: ${LINKER_OPTS}"
# build benchmark binary
# assuming the configure has set up the NDK and SDK correctly
bazel build -c opt ${LINKER_OPTS} \
  tensorflow/lite/tools/benchmark:benchmark_model

cd ${DIR}

cp "$1/bazel-bin/tensorflow/lite/tools/benchmark/benchmark_model" "$2"


#!/bin/sh

. ./scripts.inc

set -e

lclear

if [ -z "$USE_CC" ]; then
  for cc in $full_compilers_list; do
    if which $cc; then
      USE_CC="$cc" NO_CLEAR=true "$0" "$@"
    fi
  done
else
  if [ "$EXCLUDE_BENCHMARKS" = true ]; then
    for f in `find fatal -name \*.cpp|grep -v '/.*/.*benchmark/'`; do
      CC_OPT="-O0" USE_CC="$USE_CC" NO_CLEAR=true ./compile.sh "$f" "$@"
    done
  else
    for f in `find fatal -name \*.cpp`; do
      CC_OPT="-O0" USE_CC="$USE_CC" NO_CLEAR=true ./compile.sh "$f" "$@"
    done
  fi
fi


#!/bin/bash

. ./scripts.inc

set -e

if [ -z "$1" ]; then
  echo "Usage: $0 source_file"
  exit 1
fi

if [ -z "$USE_CC" ]; then
  export USE_CC="$default_compiler"
fi

CC_IS_CLANG=false
if [ "${USE_CC:0:5}" = "clang" ]; then
  CC_IS_CLANG=true
fi

if [ -z "$USE_STD" ]; then
  export USE_STD="c++14"
fi

CC_STDLIB=""
if [ "$USE_STDLIB" ]; then
  CC_STDLIB="-stdlib=$USE_STDLIB"
fi

file_name="$1"
shift
base_dir="/tmp/.build/$USE_CC/$USE_STD"
out_dir="$base_dir/`dirname "$file_name"`"
link_dir="/tmp/.bin"

if [ ! -d "$out_dir" ]; then
  mkdir -p "$out_dir"
fi

if [ -e "$link_dir" ]; then
  rm -rf "$link_dir"
fi
ln -s "$base_dir" "$link_dir"

out_binary="$out_dir/`basename "$file_name" .cpp`"

lclear

if [ -z "$CC_OPT" ]; then
  CC_OPT="-O0"
fi

CC_ARGS="-o $out_binary $CC_ARGS $CC_OPT -g -pthread -ftemplate-depth-1024 -ftemplate-backtrace-limit=0"

if [ "$CC_IS_CLANG" == true ]; then
  CC_ARGS="$CC_ARGS -ferror-limit=1"
fi

if [ "$PRE_PROC" = "true" ]; then
  CC_ARGS="-E"
fi

if [ "$USE_CCACHE" = "true" ] && [ -e "$out_binary" ]; then
  echo "using cached version of $file_name: $out_binary"
else
  echo -n "started: "; date
  if [ "$BE_LENIENT" == "true" ]; then
    set +e
  fi
  set -x
  time "$USE_CC" $CC_ARGS -Wall -Werror -Wextra "-std=$USE_STD" $CC_STDLIB -I . "$file_name" 2>&1
  set +x
  set -e
  echo -n "finished: "; date
fi

if [ ! -e "$out_binary" ] && [ "$BE_LENIENT" != "true" ]; then
  echo "binary for $file_name was not properly built"
  exit 1
fi

if [ "$DO_RUN" = "true" ]; then
  "$out_binary" "$@"
fi


#!/bin/bash

. ./scripts.inc

set -e

cc="$1"
if [ -z "$cc" ]; then
  echo "Usage: $0 compiler"
  exit 1
fi

if ! which $cc; then
  echo "no $cc installed"
  exit 1
fi

cpp_std="$2"

base_dir="/tmp/_build/$cc/$cpp_std"

if [ -e "$base_dir" ]; then
  rm -rf "$base_dir"
fi

echo "compiler: $cc"
echo "standard: $cpp_std"
$cc --version
USE_CC="$cc" USE_STD="$cpp_std" USE_CCACHE=true NO_CLEAR=true ./validate.sh


#!/bin/sh

. ./scripts.inc

if [ -z "$USE_STD" ]; then
  export USE_STD="$(flag_std_cpp14 $default_compiler)"
fi

file_name="demo/$1.cpp"
shift

DO_RUN=true ./compile.sh "$file_name" "$@"


#!/bin/bash

. ./scripts.inc

set -e

lclear

for cc in $full_compilers_list; do
  for std in `flag_std_cpp14 $cc` `flag_std_cpp17 $cc`; do
    NO_CLEAR=true USE_CC="$cc" USE_STD="$std" ./compile.sh "$@"
  done
done


#!/bin/bash

. ./scripts.inc

set -e

lclear

for cc in $full_compilers_list; do
  for std in `flag_std_cpp14 $cc` `flag_std_cpp17 $cc`; do
    NO_CLEAR=true USE_CC="$cc" USE_STD="$std" ./test.sh "$@"
  done
done


#!/bin/sh

. ./scripts.inc

while [ "$1" ]; do
  DO_RUN=true ./compile.sh lesson/$1.cpp
  shift
done


#!/bin/bash

. ./scripts.inc

set -e

for cc in $full_compilers_list; do
  for std in `flag_std_cpp14 $cc` `flag_std_cpp17 $cc`; do
    echo "## contbuild $cc $std"
    EXCLUDE_BENCHMARKS=true ./contbuild.sh "$cc" "$std"
    echo
    echo
  done
done


#!/bin/sh

. ./scripts.inc

set -e

if [ -z "$1" ]; then
  echo "Usage: $0 source_file"
  exit 1
fi

if [ -z "$USE_STD" ]; then
  export USE_STD="c++14"
fi

export USE_CC="templight"

file_name="$1"
shift
base_dir="/tmp/_build/$USE_CC/$USE_STD"
out_dir="$base_dir/`dirname "$file_name"`"

if [ ! -d "$out_dir" ]; then
  mkdir -p "$out_dir"
fi

out_path="$out_dir/`basename "$file_name" .cpp`"
out_binary="${out_path}.o"
out_prof="${out_binary}.memory.trace.pbf"

lclear

echo -n "started: "; date
set -x
templight++ -Xtemplight -profiler -Xtemplight -memory -Xtemplight -ignore-system -o "$out_binary" -O2 -Wall -Werror "-std=$USE_STD" -I . -c "$file_name" 2>&1
set +x
echo -n "finished: "; date
echo "results written to $out_prof"


# shellcheck disable=SC1113
#/bin/sh

. ./scripts.inc

set -e

lclear

no_build_flag=""
for cc in $short_compilers_list; do
  NO_CLEAR=true CC_OPT="-O0" USE_CC="$cc" ./validate.sh "$no_build_flag" "$@"
  if [ -z "$no_build_flag" ]; then
    no_build_flag="nobuild"
  fi
done


#!/bin/bash

. ./scripts.inc

set -e

if [ "$1" ]; then
  full_compilers_list="$@"
fi

if [ -z "$BE_LENIENT" ]; then
  export BE_LENIENT=true
fi

for cc in $full_compilers_list; do
  for std in `flag_std_cpp14 $cc` `flag_std_cpp17 $cc`; do
    echo "## full build $cc $std"
    USE_CC="$cc" USE_STD="$std" USE_CCACHE=true NO_CLEAR=true ./build.sh
    for f in `find demo -name '*.cpp'`; do
      USE_CC="$cc" USE_STD="$std" USE_CCACHE=true NO_CLEAR=true ./compile.sh "$f"
    done
    echo
    echo
  done
done


#!/bin/sh

. ./scripts.inc

set -e

lclear

if [ -z "$CC_OPT" ]; then
  export CC_OPT='-O0'
fi

if [ -z "$1" ]; then
  if [ -z "$USE_CC" ]; then
    for cc in $short_compilers_list; do
      for f in `find . -name \*_test.cpp`; do
        USE_CC="$cc" NO_CLEAR=true "$0" "$f" "$@"
      done
    done
  else
    for f in `find . -name \*_test.cpp`; do
      USE_CC="$USE_CC" NO_CLEAR=true "$0" "$f" "$@"
    done
  fi
elif [ -z "$2" ]; then
  test_basename="`basename "$1" .cpp`"
  if ! [ -e "$1" ]; then
    test_name="$1"
    test_path="fatal/test/${test_name}_test.cpp"
    if [ -e "$test_path" ]; then
      shift
      "$0" "$test_path"
      exit 0
    else
      echo "test $test_basename not found">&2
      exit 1
    fi
  fi
  PRE_PROC="$PRE_PROC" USE_CC="$USE_CC" NO_CLEAR=true DO_RUN=true ./compile.sh "$1"
elif [ "$1" ] && [ "$2" ]; then
  while [ "$1" ] && [ "$2" ]; do
    dir_name="$1"
    test_name="$2"
    shift
    shift
    "$0" "fatal/$dir_name/test/${test_name}_test.cpp"
  done
else
  echo "no valid tests given" >&2
fi


# shellcheck disable=SC1113
#/bin/sh

. ./scripts.inc

set -xe

skip_test=false
skip_build=false
skip_demo=false
while [ "$1" ]; do
  if [ "$1" = "notest" ]; then
    skip_test=true
  elif [ "$1" = "nobuild" ]; then
    skip_build=true
  elif [ "$1" = "nodemo" ]; then
    skip_demo=true
  fi

  shift
done

run_validation() {
  cc="$1"

  if ! which "$cc"; then
    return
  fi

  lclear

  if [ "$skip_build" != "true" ]; then
    CC_OPT="-O0" USE_CC="$cc" NO_CLEAR=true ./build.sh
  fi

  if [ "$skip_test" != "true" ]; then
    CC_OPT="-O0" USE_CC="$cc" NO_CLEAR=true ./test.sh
  fi

  if [ "$skip_demo" != "true" ]; then
    for demo in ytse_jam; do
      echo -n | CC_OPT="-O0" USE_CC="$cc" NO_CLEAR=true ./demo.sh $demo
    done
  fi
}

if [ "$USE_CC" ]; then
  run_validation "$USE_CC"
else
  for cc in $full_compilers_list; do
    run_validation "$cc"
  done
fi


#!/usr/bin/env nix-shell
#! nix-shell -i bash shell.nix

# This script sets up the build environment by invoking nix-shell shell.nix
# and then runs the hadrian executable.

function rl {
    TARGET_FILE="$1"

    cd "$(dirname "$TARGET_FILE")"
    TARGET_FILE="$(basename "$TARGET_FILE")"

    # Iterate down a (possible) chain of symlinks
    while [ -L "$TARGET_FILE" ]
    do
        TARGET_FILE="$(readlink "$TARGET_FILE")"
        cd "$(dirname "$TARGET_FILE")"
        TARGET_FILE="$(basename "$TARGET_FILE")"
    done

    # Compute the canonicalized name by finding the physical path
    # for the directory we're in and appending the target file.
    PHYS_DIR="$(pwd -P)"
    RESULT="$PHYS_DIR/$TARGET_FILE"
    echo "$RESULT"
}

absoluteRoot="$(dirname "$(rl "$0")")"
echo $absoluteRoot
cd "$absoluteRoot"

hadrian         \
  --directory="$absoluteRoot/.." \
  "$@"


#!/bin/sh

EXPECTED_VERSION="$1"

# Our shared libraries are currently executable (is that a bug?), so
# we exclude anything that looks like a shared library
for f in `find bindisttest/a/b/c -type f -perm -u+x ! -name '*.so' ! -name '*.dylib' ! -name '*.dll'`
do
    if grep -q '("GHC RTS", "YES")' "$f"
    then
        # Looks like a GHC executable. Is it for the right version?
        THIS_VERSION=`./$f +RTS --info | grep '"GHC version"' | sed -e 's/^ ,("GHC version", "//' -e 's/")$//'`
        if [ "$THIS_VERSION" != "$EXPECTED_VERSION" ]
        then
            echo "Bad GHC version '$THIS_VERSION' for '$f'" >&2
            exit 1
        fi
    fi
done


#!/usr/bin/env bash

CABAL=cabal
CABFLAGS="--disable-documentation --disable-profiling --disable-library-profiling"

# It is currently more robust to pass Cabal an absolute path to the project file.
PROJ="$PWD/hadrian/cabal.project"

set -euo pipefail

if ! [ -f "$PROJ" ]; then
    echo "Current working directory must be GHC's top-level folder"
    exit 2
fi

if ! type "$CABAL" > /dev/null; then
    echo "Please make sure 'cabal' is in your PATH"
    exit 2
fi

CABVERSTR=$("$CABAL" --numeric-version)
CABVER=( ${CABVERSTR//./ } )

if [ "${CABVER[0]}" -gt 2 -o "${CABVER[0]}" -eq 2 -a "${CABVER[1]}" -ge 2 ];
then
    "$CABAL" --project-file="$PROJ" new-build $CABFLAGS -j exe:hadrian
    # use new-exec instead of new-run to make sure that the build-tools (alex & happy) are in PATH
    "$CABAL" --project-file="$PROJ" new-exec  $CABFLAGS    hadrian -- \
        --directory "$PWD" \
        "$@"
else
    echo "Cabal version is too old; you need at least cabal-install 2.2"
    exit 2
fi


#!/usr/bin/env bash

# By default on Linux/MacOS we build Hadrian using Cabal
(. "hadrian/build.cabal.sh" "$@")


#!/usr/bin/env bash

set -euo pipefail

# readlink on os x, doesn't support -f, to prevent the
# need of installing coreutils (e.g. through brew, just
# for readlink, we use the follownig substitute.
#
# source: http://stackoverflow.com/a/1116890
function rl {
    TARGET_FILE="$1"

    cd "$(dirname "$TARGET_FILE")"
    TARGET_FILE="$(basename "$TARGET_FILE")"

    # Iterate down a (possible) chain of symlinks
    while [ -L "$TARGET_FILE" ]
    do
        TARGET_FILE="$(readlink "$TARGET_FILE")"
        cd "$(dirname "$TARGET_FILE")"
        TARGET_FILE="$(basename "$TARGET_FILE")"
    done

    # Compute the canonicalized name by finding the physical path
    # for the directory we're in and appending the target file.
    PHYS_DIR="$(pwd -P)"
    RESULT="$PHYS_DIR/$TARGET_FILE"
    echo "$RESULT"
}

absoluteRoot="$(dirname "$(rl "$0")")"

HADRIAN_NIX=YES ${absoluteRoot}/build.stack.sh


#!/usr/bin/env bash

set -euo pipefail

# readlink on os x, doesn't support -f, to prevent the
# need of installing coreutils (e.g. through brew, just
# for readlink, we use the follownig substitute.
#
# source: http://stackoverflow.com/a/1116890
function rl {
    TARGET_FILE="$1"

    cd "$(dirname "$TARGET_FILE")"
    TARGET_FILE="$(basename "$TARGET_FILE")"

    # Iterate down a (possible) chain of symlinks
    while [ -L "$TARGET_FILE" ]
    do
        TARGET_FILE="$(readlink "$TARGET_FILE")"
        cd "$(dirname "$TARGET_FILE")"
        TARGET_FILE="$(basename "$TARGET_FILE")"
    done

    # Compute the canonicalized name by finding the physical path
    # for the directory we're in and appending the target file.
    PHYS_DIR="$(pwd -P)"
    RESULT="$PHYS_DIR/$TARGET_FILE"
    echo "$RESULT"
}

absoluteRoot="$(dirname "$(rl "$0")")"
cd "$absoluteRoot"

stack build --no-library-profiling ${HADRIAN_NIX:+--nix}

stack exec hadrian --              \
    --directory "$absoluteRoot/.." \
    "$@"


#!/bin/sh

detect_cpu_count () {
    if [ "$CPUS" = "" ]; then
        # Windows standard environment variable
        CPUS="$NUMBER_OF_PROCESSORS"
    fi

    if [ "$CPUS" = "" ]; then
        # Linux
        CPUS=`getconf _NPROCESSORS_ONLN 2>/dev/null`
    fi

    if [ "$CPUS" = "" ]; then
        # FreeBSD
        CPUS=`getconf NPROCESSORS_ONLN 2>/dev/null`
    fi

    if [ "$CPUS" = "" ]; then
        # nothing helped
        CPUS="1"
    fi
}

detect_cpu_count
echo "$CPUS"


#!/usr/bin/env bash

tarball_dir='ghc-tarballs'
missing_files=0

# see #12502
if test -z "$FIND"; then FIND="find"; fi

fail() {
    echo >&2
    echo "$1" >&2
    exit 1
}

download_file() {
    local file_url="$1"
    local dest_file="$2"
    local description="$3"
    local extra_curl_opts="$4"
    local backup_url="$5"
    local dest_dir="$(dirname $dest_file)"

    if ! test -f "${dest_file}"
    then
        local curl_cmd="curl -f -L ${file_url} -o ${dest_file} --create-dirs -# ${extra_curl_opts}"
        if test -n "${backup_url}"; then
            local curl_cmd_bnk="curl -f -L ${backup_url} -o ${dest_file} --create-dirs -# ${extra_curl_opts}"
        else
            local curl_cmd_bnk="true"
        fi

        if test "$download" = "0"
        then
            echo "ERROR: Missing ${description}" >&2
            echo "${file_url}"
            missing_files=1
            return
        else
            echo "Downloading ${description} to ${dest_dir}..."
            $curl_cmd || echo "Checking repo.msys2.org instead of Haskell.org..." && $curl_cmd_bnk || {
                rm -f "${dest_file}"
                fail "ERROR: Download failed."
                exit 1
            }
        fi
    fi

    local sig_file="${dest_file}.sig"
    if test "$sigs" = "1" -a ! -f "$sig_file"
    then
        echo "Downloading ${description} (signature) to ${dest_dir}..."
        local curl_cmd="curl -f -L ${file_url}.sig -o ${sig_file} --create-dirs -# ${extra_curl_opts}"
        if test -n "${backup_url}"; then
            local curl_cmd_bnk="curl -f -L ${backup_url} -o ${sig_file} --create-dirs -# ${extra_curl_opts}"
        else
            local curl_cmd_bnk="true"
        fi
        $curl_cmd || echo "Checking repo.msys2.org instead of Haskell.org..." && $curl_cmd_bnk || {
                rm -f "${dest_file}.sig"
                fail "ERROR: Download failed."
                exit 1
            }
    fi

    if test "$verify" = "1"
    then
        grep "${dest_file}$" mk/win32-tarballs.md5sum | md5sum --quiet -c - ||
            fail "ERROR: ${description} appears to be corrupted, please delete it and try again."
    fi
}

download_mingw() {
    local mingw_base_url_primary="https://downloads.haskell.org/~ghc/mingw"
    local mingw_base_url_secondary="http://repo.msys2.org/mingw"

    if test "$mingw_arch" = "sources"
    then
        mingw_url_tmp=`echo "$1" | sed -e 's/-any\.pkg\.tar\.xz/\.src\.tar\.gz/' \
                                       -e 's/-sources-/-/' \
                                       -e 's/-libwinpthread-git-/-winpthreads-git-/' `
        local mingw_url="${mingw_base_url_primary}/${mingw_url_tmp}"
        local mingw_url_backup="${mingw_base_url_secondary}/${mingw_url_tmp}"
    else
        local mingw_url="${mingw_base_url_primary}/$1"
        local mingw_url_backup="${mingw_base_url_secondary}/$1"
    fi

    local mingw_toolchain="$(basename $mingw_url)"
    local mingw_w64="${tarball_dir}/${tarball_dest_dir}/${mingw_toolchain}"

    download_file "${mingw_url}" "${mingw_w64}" "${mingw_toolchain}" "" "${mingw_url_backup}"

    # Mark the tree as needing updates by deleting the folder
    if test -d inplace/mingw && test inplace/mingw -ot "$mingw_w64" ; then
        echo "In-tree MinGW-w64 tree requires updates..."
        rm -rf inplace/mingw
    fi
}

download_tarballs() {
    local package_prefix="mingw-w64"
    local format_url="/${mingw_arch}/${package_prefix}-${mingw_arch}"

    download_mingw "${format_url}-crt-git-5.0.0.4795.e3d96cb1-1-any.pkg.tar.xz"
    download_mingw "${format_url}-winpthreads-git-5.0.0.4850.d1662dc7-1-any.pkg.tar.xz"
    download_mingw "${format_url}-headers-git-5.0.0.4966.1eee2140-1-any.pkg.tar.xz"
    download_mingw "${format_url}-libwinpthread-git-5.0.0.4850.d1662dc7-1-any.pkg.tar.xz"
    download_mingw "${format_url}-zlib-1.2.8-9-any.pkg.tar.xz"
    download_mingw "${format_url}-isl-0.18-1-any.pkg.tar.xz"
    download_mingw "${format_url}-mpfr-3.1.6-1-any.pkg.tar.xz"
    download_mingw "${format_url}-gmp-6.1.2-1-any.pkg.tar.xz"
    download_mingw "${format_url}-binutils-2.29.1-1-any.pkg.tar.xz"
    download_mingw "${format_url}-libidn2-2.0.4-1-any.pkg.tar.xz"
    download_mingw "${format_url}-gcc-7.2.0-1-any.pkg.tar.xz"

    # Upstream is unfortunately quite inconsistent in naming
    if test "$mingw_arch" != "sources"; then
        download_mingw "${format_url}-mpc-1.0.3-2-any.pkg.tar.xz"
        download_mingw "${format_url}-gcc-libs-7.2.0-1-any.pkg.tar.xz"
        download_file "https://downloads.haskell.org/~ghc/mingw/ghc-perl-1.tar.gz" "ghc-tarballs/perl/ghc-perl-1.tar.gz" "Windows Perl binary distributions" "" ""
    else
        local format_url="${mingw_base_url}/${mingw_arch}/${package_prefix}"
        download_mingw "${format_url}-i686-mpc-1.0.3-2.src.tar.gz"
        download_mingw "${format_url}-x86_64-mpc-1.0.3-2.src.tar.gz"
    fi

    if ! test "$missing_files" = "0"
    then
        exit 2
    fi
}

download_i386() {
    mingw_arch="i686"
    tarball_dest_dir="mingw-w64/x86"
    download_tarballs
}

download_x86_64() {
    mingw_arch="x86_64"
    tarball_dest_dir="mingw-w64/x86_64"
    download_tarballs
}

download_sources() {
    mingw_arch="sources"
    tarball_dest_dir="mingw-w64/sources"
    download_tarballs
}

sync_binaries_and_sources() {
    gpg --recv-key  5F92EFC1A47D45A1

    # ensure sources are downloaded
    sigs=1
    download_i386
    download_x86_64
    verify=0
    download_sources

    for f in $($FIND ghc-tarballs/mingw-w64 -iname '*.sig'); do
        echo "Verifying $f"
        gpg --verify $f
    done

    md5sum `$FIND ghc-tarballs -type f -a -not -iname '*.sig'` >| mk/win32-tarballs.md5sum
    chmod -R ugo+rX ghc-tarballs

    rsync -av ghc-tarballs/mingw-w64/* downloads.haskell.org:public_html/mingw
    for f in $($FIND ghc-tarballs/mingw-w64); do
        curl -XPURGE http://downloads.haskell.org/~ghc/mingw/$f
    done
}

show_hashes_for_binaries() {
    $FIND ghc-tarballs/ -iname "*.*" | xargs md5sum | grep -v "\.sig" | sed -s "s/\*//"
}

usage() {
    echo "$0 - Download GHC mingw toolchain tarballs"
    echo
    echo "Usage: $0 <action> [<arch>]"
    echo
    echo "Where <action> is one of,"
    echo ""
    echo "    download     download the necessary tarballs for the given architecture"
    echo "    fetch        download the necessary tarballs for the given architecture but doesn't verify their md5."
    echo "    verify       verify the existence and correctness of the necessary tarballs"
    echo "    hash         generate md5 hashes for inclusion in win32-tarballs.md5sum"
    echo "    sync         upload packages downloaded with 'fetch mirror' to haskell.org"
    echo ""
    echo "and <arch> is one of i386, x86_64,all or mirror (which includes sources)"
}

case $1 in
    download)
        download=1
        verify=1
        sigs=0
        ;;
    fetch)
        download=1
        verify=0
        ;;
    verify)
        download=0
        verify=1
        ;;
    sync)
        download=1
        verify=0
        sync=1
        ;;
    hash)
        show_hashes_for_binaries
        exit 1
        ;;
    *)
        usage
        exit 1
        ;;
esac

case $2 in
    i386)
        download_i386
        ;;
    x86_64)
        download_x86_64
        ;;
    all)
        download_i386
        download_x86_64
        ;;
    mirror)
        sigs=1
        download_i386
        download_x86_64
        verify=0
        download_sources
        show_hashes_for_binaries
        ;;
    *)
        if test "$sync" = "1"; then
            sync_binaries_and_sources
        else
            usage
            exit 1
        fi
        ;;
esac


#! /bin/sh

# something like this...
for i in mod*.hs; do
  if ! test -f ${i%.hs}.output; then
     echo "test('${i%.hs}', normal, compile, [''])"
  else if grep error ${i%.hs}.output >/dev/null; then
     echo "test('${i%.hs}', normal, compile_fail, [''])"
  else
     echo "test('${i%.hs}', normal, compile, [''])"
  fi fi
done


#!/bin/sh -xe

# Runs ghc-stage2 with GHCi settings that allow GHC to be loaded and run in the
# interpreter. Options provided on the command-line will be passed directly to
# the GHCi invocation.

# Note that this script is intended to be run from the root of the GHC repo,
# like this:

# ./utils/ghc-in-ghci/run.sh

# This is substantially faster than doing an actual compile, and so can aid in
# tighter development iterations. It can be made even faster by specifying "-jN"
# for parallelism. Typically choosing an N value close to the number of logical
# CPU cores you have leads to faster loads. Here's how to specify -j:

# ./utils/ghc-in-ghci/run.sh -j4

# The script will also run `:load Main`, to load GHC's main module. After that,
# running `main` will run an inner GHCi, because there is a default `:set args
# --interactive ...`. To override this, use `:set args ...` or `:main ...`.

# If you don't want to wait for `:load Main`, since you want to load some other
# module, then you can use `Ctrl+C` to cancel the initial load.

# Look in two common locations for a GHC installation (the results of using
# the make- and Hadrian-based build systems, respectively).
if [ -d ./inplace/lib ]; then
  GHC_BIN=./inplace/bin/ghc-stage2
  _GHC_TOP_DIR=./inplace/lib
elif [ -d ./_build/stage1/lib ]; then
  GHC_BIN=./_build/stage1/bin/ghc
  _GHC_TOP_DIR=./_build/stage1/lib
else
  echo "Could not find GHC installation"
  exit 1
fi

exec ${GHC_BIN} \
    --interactive \
    -ghci-script ./utils/ghc-in-ghci/settings.ghci \
    -ghci-script ./utils/ghc-in-ghci/load-main.ghci \
    +RTS -A128m -RTS \
    "$@"


#!/usr/bin/env bash
#
# llvm-target generator
#
# Author: Moritz Angermann <moritz.angermann@gmail.com>
#
# This file generates the `llvm-targets` file, which contains the
# data-layout, cpu and attributes for the target.  This is done by
# querying `clang` for the data-layout, cpu and attributes based
# on a given target.
#
# To utilize it run it as
#
#  $ ./gen-data-layout.sh > llvm-targets
#
# Add missing targets to the list below to have them included in
# llvm-targets file.

# Target sets for which to generate the llvm-targets file
TARGETS=(
    # Windows x86
    "i386-unknown-windows" "i686-unknown-windows" "x86_64-unknown-windows"

    # Linux ARM
    "arm-unknown-linux-gnueabihf" "armv6-unknown-linux-gnueabihf" "armv6l-unknown-linux-gnueabihf"
    "armv7-unknown-linux-gnueabihf" "armv7a-unknown-linux-gnueabi" "armv7l-unknown-linux-gnueabihf"
    "aarch64-unknown-linux-gnu" "aarch64-unknown-linux"
    # Linux x86
    "i386-unknown-linux-gnu" "i386-unknown-linux" "x86_64-unknown-linux-gnu" "x86_64-unknown-linux"
    # Linux Android
    "armv7-unknown-linux-androideabi" "aarch64-unknown-linux-android"
    # Linux ppc64le
    "powerpc64le-unknown-linux"

    # FreeBSD amd64
    "amd64-portbld-freebsd"
    "x86_64-unknown-freebsd" # See #15718

    # QNX
    "arm-unknown-nto-qnx-eabi"

    # macOS
    "i386-apple-darwin" "x86_64-apple-darwin"
    # iOS
    "armv7-apple-ios arm64-apple-ios" "i386-apple-ios x86_64-apple-ios"

    # FreeBSD ARM
    "aarch64-unknown-freebsd" "armv6-unknown-freebsd-gnueabihf" "armv7-unknown-freebsd-gnueabihf"
)

# given the call to clang -c11 that clang --target -v generates,
# parse the -target-cpu <CPU> and -target-feature <feature> from
# the output.
function get_cpu_and_attr() {
    # echo $@
    while [ "$#" -gt 0 ]; do
        case "$1" in
            -target-cpu) CPU=$2; shift 2;;
            -target-feature)
                # translate clang to opt/llc target features
                case "$2" in
                    # we don't have support in GHC for proper soft-float.
                    # if we extend the `llvm-target` file to contain two
                    # additional columns for opt and llc flags, we could
                    # pass -float-abi=soft; However ghc will use float
                    # registers unconditionally on arm, and as such true
                    # soft float with the registerised llvm backend is
                    # currently not possible.
                    +soft-float-abi) shift 2;;
                    *) ATTR+=("$2"); shift 2;;
                esac
                ;;
            *) shift 1;;
        esac
    done
}

# first marker to discriminate the first line being outputted.
FST=1
# a dummy file to use for the clang invocation.
FILE=_____dummy.c
touch $FILE

for target in "${TARGETS[@]}"; do
    # find the cpu and attributes emitted by clang for the given $target
    CPU=""
    ATTR=()
    args=$(clang --target=$target -S $FILE -o /dev/null -v 2>&1 |grep $FILE)
    get_cpu_and_attr $args

    # find the data-layout from the llvm code emitted by clang.
    dl=$(clang --target=$target -S $FILE -emit-llvm -o -|grep datalayout |awk -F\  '{ print $4 }')
    # GNU and Apple/LLVM can't agree on the aarch64 target.
    # aarch64-apple-ios, is understood by autotools but not by LLVM.
    # arm64-apple-ios, is understood by LLVM, but not by autotools.
    #
    # therefore, while we query clang with arm64-apple-ios, we put
    # aarch64-apple-ios into the llvm-target list, as that is what
    # we have to configure ghc with --target with anyway.  Also we
    # want to retain the GNU naming for compatibility with libraries
    # that use autotools.
    if [ "$target" == "arm64-apple-ios" ]; then
       target="aarch64-apple-ios"
    fi
    if [ $FST -eq 1 ]; then
        echo "[(\"${target}\", ($dl, \"$CPU\", \"${ATTR[*]}\"))"
        FST=0
    else
        echo ",(\"${target}\", ($dl, \"$CPU\", \"${ATTR[*]}\"))"
    fi
done
rm $FILE
echo "]"


#!/bin/sh
apt-get update
apt-get build-dep -y ghc


#!/bin/sh
yum update -y
yum install -y glibc-devel ncurses-devel gmp-devel autoconf automake libtool \
 gcc make perl python ghc git


#!/bin/bash
#
# This script will verify that the packages in ghc,
# correspond to packages on hackage.
rm -fR ghc-packages hackage-packages package-diffs
mkdir -p ghc-packages hackage-packages package-diffs
# We'll skip Cabal and tarballs, while looking only at packages in libraries
# that we reference as gitmodules.
for lib in $(git submodule status|grep libraries|grep -v tarballs|grep -v Cabal|awk -F\  '{ print $2 }'); do
    (cd $lib && cabal new-sdist -o ../../ghc-packages);
done

for pkg in $(cd ghc-packages && ls *.tar.gz); do
    PKG=${pkg%%.tar.gz}
    (cd hackage-packages && cabal get --pristine ${PKG})
    (cd hackage-packages/${PKG} && git init && git add . && git commit -q -m "hackage packages" && rm -fR *)
    (cd hackage-packages && tar xzf ../ghc-packages/$pkg)
    (cd hackage-packages/${PKG} && git -c core.fileMode=false diff > ../$PKG.patch)
done
find hackage-packages -name "*.patch" -not -empty -type f -print -exec false {} +


# Mini-driver for Haddock

# needs the following variables:
#	HADDOCKLIB
#	HADDOCKBIN

$HADDOCKBIN --lib $HADDOCKLIB ${1+"$@"}


# mini script for building the relocatable Windows binary distribution.
#
#    sh build-windows-dist.sh
#
# NB. the Cabal that shipped with GHC 6.6 isn't enough for this, because it
# is missing this patch:
#
# Fri Oct 13 11:09:41 BST 2006  Simon Marlow <simonmar@microsoft.com>
#   * Fix getDataDir etc. when bindir=$prefix
#
# So you need to use a more recent Cabal.  GHC 6.6 is fine for building the
# package, though.

ghc --make Setup
./Setup configure --prefix=`pwd`/install --bindir='$prefix' --libdir='$prefix' --datadir='$prefix'
./Setup build
./Setup install
echo Now zip up `pwd`/install as "haddock-<version>-Win32.zip"


# Put the Happy-generated .hs files in the right place in the source dist.
set -e
rm -f dist/haddock-*.tar.gz
rm -rf dist/haddock-*/
./Setup sdist
cd dist
tar xvzf haddock-*.tar.gz
cd haddock-*/
mkdir dist
mkdir dist/build
mv haddock dist/build
cd ..
tar cvzf haddock-*.tar.gz haddock-*/

# Steps for doing a release:
#  * Update version number in .cabal, doc/haddock.xml
#  * Update CHANGES
#  * Source:
#    - do the above
#    - upload the dist to haskell.org:haddock/dist/${version}
#    - scp CHANGES haskell.org:haddock/CHANGES.txt
#  * Binaries:
#    - build the Windows binary zip (see build-windows-dist.sh)
#    - scp haddock-<version>-Win32.zip haskell.org:haddock/dist
#  * Documentation:
#    - cd doc
#    - make html
#    - mv haddock haddock-html
#    - tar cvzf haddock-doc-html-${version}.tar.gz haddock-html
#    - scp haddock-doc-html-${version}.tar.gz www.haskell.org:../haskell/haddock/doc
#    - ssh haskell.org
#        - cd haddock/doc
#        - tar xvzf haddock-doc-html-${version}.tar.gz
#        - rm -rf html-OLD
#        - mv html html-OLD && mv haddock-html html
#  * Update the web page (~/darcs/www/haddock/index.html), and push it


#!/usr/bin/env bash

# FBOSS is now built using fbcode_builder. Thus, just invoke fbcode_builder
# getdeps.py to build fboss here.

TOOLCHAIN_DIR=/opt/rh/devtoolset-8/root/usr/bin
if [[ -d "$TOOLCHAIN_DIR" ]]; then
    PATH="$TOOLCHAIN_DIR:$PATH"
fi

FBOSS_DIR=$(dirname "$0")
GETDEPS_PATHS=(
    "$FBOSS_DIR/build/fbcode_builder/getdeps.py"
    "$FBOSS_DIR/../../opensource/fbcode_builder/getdeps.py"
)
for getdeps in "${GETDEPS_PATHS[@]}"; do
    if [[ -x "$getdeps" ]]; then
        exec "$getdeps" build fboss --current-project fboss "$@"
    fi
done
echo "Could not find getdeps.py!?" >&2
exit 1


#!/bin/bash

$1 --version | grep "Package Version"


#!/bin/bash

prefixtext() {
  infile=$1
  prefix="$2"
  echo "${prefix}// SOURCE: $infile"
  echo "${prefix}R\"__CONFIG__("
  while IFS= read -r line;
  do
    echo "${prefix}$line"
  done < "$infile"
  echo -n "${prefix})__CONFIG__\""
}

gencpp() {
  inf=$1
  outf=$2
  namespace=$3
  func=$4
  if [ ! -e "$inf" ]; then
    echo "$inf does not exist"
    exit 1
  fi
  {
    echo "// Copyright 2021-present Facebook. All Rights Reserved."
    echo "// THIS FILE IS AUTOGENERATED DO NOT MODIFY"
    echo "// GENERATED BY: \`$0 $*\`"
    echo "#include <string>"
    echo "#include <vector>"
    echo "namespace $namespace {"
    if [ -d "$inf" ]; then
      echo "const std::vector<std::string> $func() {"
      echo "  return {"
      for f in "$inf"/*.json; do
        prefixtext "$f" "    "
        echo ","
      done
      echo "  };"
    else
      echo "const std::string $func() {"
      echo -n "  return "
      prefixtext "$inf" "  "
      echo ";"
    fi
    echo "}"
    echo "}"
  } > "$outf"
}

INSTALL_DIR=""
for i in "$@"; do
  case $1 in
    --install_dir=*)
      INSTALL_DIR="${i#*=}"
      shift # past argumen=value
      ;;
    *)
      echo "Unknown positional $1"
      exit 1
      ;;
  esac
done

SRC_DIR=$(dirname "${BASH_SOURCE[0]}")
CONFIG_DIR="./configs"
if [ -d $CONFIG_DIR ]; then
  echo "CONFIG_DIR=$CONFIG_DIR"
elif [ -d "${SRC_DIR}/configs" ]; then
  CONFIG_DIR="${SRC_DIR}/configs"
  echo "CONFIG_DIR=$CONFIG_DIR"
else
  echo "ERROR: $0 needs to be executed in project root containing configs"
  exit 1
fi
OUTPUT_DIR="."
if [ -n "$INSTALL_DIR" ]; then
  OUTPUT_DIR=$INSTALL_DIR
fi

NAMESPACE="rackmonsvc"
gencpp "$CONFIG_DIR/interface/rackmon.conf" "$OUTPUT_DIR/GeneratedRackmonInterfaceConfig.cpp" "$NAMESPACE" getInterfaceConfig
gencpp "$CONFIG_DIR/interface/rackmon_pls.conf" "$OUTPUT_DIR/GeneratedRackmonPlsConfig.cpp" "$NAMESPACE" getRackmonPlsConfig
gencpp "$CONFIG_DIR/register_map" "$OUTPUT_DIR/GeneratedRackmonRegisterMapConfig.cpp" "$NAMESPACE" getRegisterMapConfig


#!/bin/sh
# Copyright 2022-present Facebook. All Rights Reserved.

# contruct the RPM remote server URL
KERNEL_VER=$(uname -r)
YUM_KERNEL_DIR=$(echo "${KERNEL_VER}" | cut -d '_' -f 1,2)
RPM_REMOTE_SERVER_URL="https://yum.rftw0.facebook.com/yum/centos/kernel/${YUM_KERNEL_DIR}/x86_64/RPMS/"

stop_chef(){
  # Stopping chef to perform kernel upgrades. Default is at least 1 hour

  /usr/facebook/ops/scripts/chef/stop_chef_temporarily -r "To perform BSP Kmods upgrade on Darwin platform"

}

stop_platform_services(){
  # stop rackmon
  systemctl stop rackmon.service

  # stop fan_service
  systemctl stop fan_service.service

  # stop sensor_service
  systemctl stop sensor_service.service

  # stop data_corral_service
  systemctl stop data_corral_service.service

}

fan_speed_increase(){
  # since fan_service is not running to dynamically control the fan speed
  # so  we will increase the fan_speed to 70% to prevent the switch from overheating

  bash set_fan_speed.sh 70

}

stop_forwarding_stack_services(){
  # stop QSFP service
  systemctl stop qsfp_service

  # stop agent
  systemctl stop wedge_agent

}

stop_watchdog(){
  # stop watchdog
  # watchdog timer will be stopped automatically when watchdog service
  # is stopped.
  systemctl stop watchdog

}

unload_bsp_kmods(){
  # unload the I2C client drivers
  modprobe -r rook_fan_cpld blackhawk_cpld i2c_dev_sysfs amax5970 aslg4f4527

  # unload SCD and SCD subdevice drivers
  modprobe -r scd_smbus scd_leds scd_watchdog scd
}

install_bsp_kmods(){
  # Remove the old RPM
  KMOD_RPM_VER="$1"
  old_rpm=$(rpm -qa | grep arista_darwin_bsp)
  rpm -e "$old_rpm"

  # Pull the Latest kmod rpm for the current running kernel version

  # Get the context of the remote server into a file
  wget "${RPM_REMOTE_SERVER_URL}" -q -O - | grep "arista_darwin" > /tmp/remote_server_output.txt

  # remove the .x86_64.rpm since it won't be part of the rpm command
  sed -i -e 's/.x86_64.rpm//' /tmp/remote_server_output.txt

  # Sort the content of the file per date (both calendar date and time) and pull the rpm
  # for the sorting one k2 full the column with the day, month, year first
  # then  k3 pick the column with the hours and mins
  # then the most recent rpm file will be at the bottom
  rpm=$(sort -k2 -k3 /tmp/remote_server_output.txt | cut -d '>' -f 1 | cut -d '"' -f 2 | tail -1)

  #remove the tmp file since it's no longer needed
  rm -rf /tmp/remote_server_output.txt

  dnf install -y "${rpm}"
}

reload_bsp_kmods(){
  # loading scd driver should be good enough: all the relevant scd-* and
  # I2C client drivers should be loaded automatically when the corresponding
  # devices are created.
  modprobe scd
}

start_watchdog(){
  # restart the watchdog service
  systemctl start watchdog

}

start_forwarding_stack_services(){
  # start wedge_agent
  systemctl start wedge_agent

  # start qsfp service
  systemctl start qsfp_service

}

start_platform_services(){
  # start data_corral
  systemctl start data_corral_service.service

  # start sensor_service
  systemctl start sensor_service.service

  # start fan_service
  systemctl start fan_service.service

  # start rackmon
  systemctl start rackmon.service

}

# start chef
start_chef(){
  # resume chef operation
  rm -rf /var/chef/cron.default.override

}

# Drain the swich since Kernel upgrade is being treated as disruptive
# TODO: Figure out what is the command to drain switch on Darwin

# stop chef so that it doesn't restart platform services
stop_chef

# Stop platform services
stop_platform_services

# increase fan_speed
fan_speed_increase

# stop forwarding stack services
stop_forwarding_stack_services

# stop watchdog
stop_watchdog

# unload bsp kernel Modules
unload_bsp_kmods

# install new bsp kmods
install_bsp_kmods "$KMOD_RPM_VER"

# reload bsp_kmods
reload_bsp_kmods

# start watchdog service
start_watchdog

# start fowarding stack services
start_forwarding_stack_services

# start platform services
start_platform_services

# start chef
start_chef

# undrain the switch
# TODO: Figure out the command to undrain the switch


#!/bin/bash

usage() {
  echo "Usage: $0 <PWM_PERCENT> [FAN_TRAY] "
  echo "<PWM_PERCENT> : From 0 to 100 "
  echo "[FAN_TRAY] : 1, 2, 3, 4, 5 or 6."
  echo "If no FAN_TRAY is specified, all FANs will be programmed"
}

FANCPLD="/run/devmap/sensors/FAN_CPLD"
SLGCONTROLLER="/run/devmap/sensors/FS_FAN_SLG4F4527"

set -e

# Make sure we only have 1 or 2 arguments
if [ "$#" -ne 2 ] && [ "$#" -ne 1 ]; then
    usage
    exit 1
fi

# Also make sure that percent value is really between 0 and 100
if [ "$1" -lt 0 ] || [ "$1" -gt 100 ]; then
    echo "PWM_PERCENT $1: should be between 0 and 100"
    exit 1
fi

# Read FAN_TRAY value from user argument.
# If no FAN_TRAY is given, configure all FANs
if [ "$#" -eq 1 ]; then
    FAN_UNIT="1 2 3 4 5 6"
else
    if [ "$2" -le 0 ] || [ "$2" -ge 7 ]; then
        echo "Fan $2: should be between 1 and 6"
        exit 1
    fi
    FAN_UNIT="$2"
fi

# Convert input (0-100%) to PWM (0-255)
# Multiple by 2.5
step="$(printf '%.*f' 0 "$((255 * $1 / 100))")"

for unit in ${FAN_UNIT}; do
    if [ "$unit" -le 5 ]; then
        pwm="$FANCPLD/pwm${unit}"
        echo "$step" > "${pwm}"
        echo "$step will be set to ${pwm} !!!!"
        echo "Successfully set system fan ${unit} speed to $1%"
    else
        pwm="$SLGCONTROLLER/pwm"
        # Need to invert PWM setting for SLG because written value is lower duty cycle
        step="$(printf '%.*f' 0 "$((255 * (100 - $1) / 100))")"
        echo "$step" > "${pwm}"
        echo "$step will be set to ${pwm} !!!!"
        echo "Successfully set fanspinner fan speed to $1%"
    fi
done


#!/usr/bin/env bash

sudo yum install -y git gcc gcc-c++ python-devel rh-python36 openssl*
sudo yum install -y centos-release-scl-rh devtoolset-8-toolchain
sudo yum group install "Development Tools" -y
sudo yum install rpm-build rpmdevtools -y
sudo yum --enablerepo=extras install epel-release -y
sudo yum install python-pip -y
sudo pip install gitpython
sudo yum install openssl-devel -y


#!/usr/bin/env bash

sudo apt-get update
sudo apt-get install git vim gcc m4 bison flex libssl-dev python-dev pkg-config build-essential zlib1g-dev -y


#!/bin/sh
#
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#

set -eu

xcodebuild -project FBRetainCycleDetector.xcodeproj \
           -scheme FBRetainCycleDetector \
           -destination "platform=iOS Simulator,name=iPhone 8" \
           -sdk iphonesimulator \
           build test


#!/bin/sh
#
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#

set -x
set -e

cd -- "$(dirname -- "$0")"

# Download data in temp dir.
rcd_fishhook_path="$(pwd)/rcd_fishhook/"
git_fishhook_path=$(mktemp -d /tmp/rcd-fishhook.XXXXXX)
if [ $? -ne 0 ]; then
    echo "$0: Can't create temp file, exiting..."
    exit 1
fi
cd -- "$git_fishhook_path"
git clone 'git@github.com:facebook/fishhook.git'

# Update repo.
cd "${rcd_fishhook_path}"
rm -- rcd_fishhook.* || true
cp -r "${git_fishhook_path}"/fishhook/* .
rm fishhook.podspec

sed -i '' 's/fishhook_h/rcd_fishhook_h/g' fishhook.*
sed -i '' 's/fishhook\.h/rcd_fishhook\.h/g' fishhook.*
sed -i '' 's/struct rebinding/struct rcd_rebinding/g' fishhook.*
sed -E -i '' 's/(rebind_symbols(_image)?|prepend_rebindings|perform_rebinding_with_section)\(/rcd_\1\(/g' fishhook.*

mv fishhook.h rcd_fishhook.h
mv fishhook.c rcd_fishhook.c

# Clean up.
rm -rf "$git_fishhook"


#!/bin/bash
#######################
# Script to compare strings collected by the bleeding edge version of
# fbt library (babel-plugin-fbt@0.21.0) with strings collected by a previous
# version.
#
# Usage:
#   - While you are still on old babel-plugin-fbt, run `yarn fbt-collect` to
#     collect legacy strings
#   - Upgrade to babel-plugin-fbt@~0.21.0 in your package.json and run `yarn install`
#   - Run `yarn fbt-collect` to collect new strings
#   - Run `./categorize_new_strings.sh <legacy_srings.json> <new_strings.json> [--return-new-hash-key]`
#
#######################

set -euo pipefail

inputFileLegacy=$1
inputFileNew=$2
optionReturnPhrasesWithNewHashKey=""
if [[ $# -gt 2 ]]; then
  optionReturnPhrasesWithNewHashKey=$3
fi

tempFileLegacy=$inputFileLegacy.temp.json
tempFileNew=$inputFileNew.temp.json

jq '.phrases' "$inputFileLegacy" | jq '.|=sort_by(.filepath, .line_beg, .col_beg)' --sort-keys >& "$tempFileLegacy"
jq '.phrases' "$inputFileNew" | jq '.|=sort_by(.filepath, .line_beg, .col_beg)' --sort-keys >& "$tempFileNew"

node categorizeNewStrings.js \
  "$tempFileLegacy" "$tempFileNew" "$optionReturnPhrasesWithNewHashKey" \
  > "new_strings_by_category.json" && rm "$tempFileLegacy" "$tempFileNew"


#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

DIR=$( dirname "${BASH_SOURCE[0]}" )

for x in "$DIR"/*.mustache "$DIR"/**/*.mustache; do
  ruby "$DIR/validate.rb" "$x" || exit;
done


#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This script exists to generate the test_key.pem, test_cert.pem,
# ca-key.pem, and ca-cert.pem files.  It shouldn't really ever be run again
# until the year 2041 (when these certs expire)., unless you need to change
# or update attributes of the certificate (Common Name, Organization,
# whatever).

set -e

DAYS=10000

# Generate Certificate Authority Key
openssl genrsa -out ca-key.pem 2048

# Generate Self-Signed Certificate Authority Cert
openssl req -x509 -new -nodes \
    -key ca-key.pem \
    -days ${DAYS} \
    -out ca-cert.pem \
    -subj '/C=US/O=Thrift/CN=Thrift Certificate Authority'

# CA serial number
echo 00000009 > ca-cert.srl

function generateCert() {
    cat > conf.tmp <<EOF
prompt = no
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req

[req_distinguished_name]
countryName = US
stateOrProvinceName = Ohio
localityName = Hilliard
commonName = Asox Company

[v3_req]
# Extensions to add to a certificate request
# basicConstraints = CA:FALSE
# keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = IP:$3, IP:$4
EOF

    # Generate the test key
    openssl genrsa -out $1 2048

    # Generate the test key certificate request
    openssl req -new -nodes \
	-config conf.tmp \
	-key $1 \
	-days ${DAYS} \
	-out test_cert.csr \
	-subj '/C=US/O=Asox/CN=test.thrift.org'

    # Sign the test key
    openssl x509 -req \
	-extensions v3_req \
	-extfile conf.tmp \
	-days ${DAYS} \
	-in test_cert.csr \
	-CA ca-cert.pem \
	-CAkey ca-key.pem \
	-out $2

    # Clean up the signing request as well as the serial number
    rm ca-cert.srl test_cert.csr conf.tmp
}

generateCert tests-key.pem tests-cert.pem 127.0.0.1 ::1


#!/bin/sh
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

# remove --install_dir
shift 1

${PROTOC} --cpp_out="$INSTALL_DIR" "$@"

# Fix up include path
sed -i \
  's|ProtoBufBenchData.pb.h|thrift/lib/cpp2/test/ProtoBufBenchData.pb.h|g' \
  "$INSTALL_DIR"/ProtoBufBenchData.pb.cc


#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

rm -rf gen-py
../../../compiler/cpp/thrift --gen py test1.thrift || exit 1
../../../compiler/cpp/thrift --gen py test2.thrift || exit 1
PYTHONPATH=./gen-py python -c 'import foo.bar.baz' || exit 1
PYTHONPATH=./gen-py python -c 'import test2' || exit 1
PYTHONPATH=./gen-py python -c 'import test1' &>/dev/null && exit 1  # Should fail.
cp -r gen-py simple
../../../compiler/cpp/thrift -r --gen py test2.thrift || exit 1
PYTHONPATH=./gen-py python -c 'import test2' || exit 1
diff -ur simple gen-py > thediffs
file thediffs | grep -s -q empty || exit 1
rm -rf simple thediffs
echo 'All tests pass!'


#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

echo "Starting a manual test run ..."

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
DIST_DIR="$DIR/../dist"

if [[ ! -d $DIST_DIR/mac || ! -d $DIST_DIR/linux-unpacked || ! -d $DIST_DIR/win-unpacked ]]; then
    echo "ERR: Needs distributions built for Mac, Linux and Windows."
    echo "Please run in this in the desktop directory:"
    echo "$ yarn build --mac --linux --win"
    exit 1
fi

has_resources() {
    if ! tar tf "$1" | grep '[Rr]esources/app.asar' > /dev/null; then
        echo "ERR: $1 for $2 does not contain a resource bundle. Check your packfile!"
        exit 2
    fi
}

has_no_resources() {
    if (( $(tar tf "$1" | grep -cFv '[Rr]esources/app.asar') < 10 )); then
        echo "ERR: $1 for $2 has suspiciously low number of non-resource files. Check your packfile!"
        exit 2
    fi
}

echo "Build for Mac ..."

cargo run mac
has_resources core.tar.xz mac
has_no_resources frameworks.tar.xz mac
cat manifest.json

echo
echo "All good."

echo "Build for Linux ..."

cargo run linux
has_resources core.tar.xz linux
has_no_resources frameworks.tar.xz linux
cat manifest.json

echo
echo "All good."

echo "Building for Windows ..."

cargo run windows
has_resources core.tar.xz windows
has_no_resources frameworks.tar.xz windows
cat manifest.json

echo
echo "All good. Ship it."


#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

BASEDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Run from here so we know we're having fbsource in our $PWD.
cd "$BASEDIR" || exit

case $OSTYPE in
  darwin*) ./bump.mac "$@" ;;
  linux-gnu) ./bump.lnx64 "$@" ;;
  *) echo "Unknown OS. Using source version via https://haskellstack.org/" && ./bump/bump.hs "$@" ;;
esac


#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

RESULT_FILE=$1

if [ -f "$RESULT_FILE" ]; then
  rm "$RESULT_FILE"
fi
touch "$RESULT_FILE"

checksum_file() {
  openssl sha256 "$1" | awk '{print $2}'
}

FILES=()
while read -r -d ''; do
  FILES+=("$REPLY")
done < <(find . -type f \( -name "build.gradle*" -o -name "gradle-wrapper.properties" \) -print0)

# Loop through files and append checksum to result file
for FILE in "${FILES[@]}"; do
  checksum_file "$FILE" >> "$RESULT_FILE"
done

sort "$RESULT_FILE" -o "$RESULT_FILE"


#!/bin/sh
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

set -e

main () {
  local -r THIS_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
  ROOT_DIR=$(cd "$THIS_DIR" && hg root)
  source "$ROOT_DIR/xplat/sonar/scripts/setup-env.sh"

  # save current cursor location
  printf "Ensuring correct dependencies..."

  PREV_DIR="`pwd`"

  # install dependencies
  cd "$INFINITY_DIR"
  "$INSTALL_NODE_MODULES"

  # ensure electron gets installed
  node node_modules/electron/install.js

  # go back
  cd "$PREV_DIR"

  # remove correct dependencies log
  printf "\r"
}

main


#!/bin/bash -xe
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

# try to install with wget
command -v wget &>/dev/null && wget -O /tmp/retry "https://github.com/moul/retry/releases/download/v0.5.0/retry_$(uname -s)_$(uname -m)" || true

# try to install with curl
if [ ! -f /tmp/retry ]; then
  command -v curl &>/dev/null && curl -L -o /tmp/retry "https://github.com/moul/retry/releases/download/v0.5.0/retry_$(uname -s)_$(uname -m)"
fi

chmod +x /tmp/retry
/tmp/retry --version


#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

set -e

echo "âœ¨ Making a new release..."

# When starting this job from SandcastleFlipperAutoReleaseCommand, we pass in the revision to release
SANDCASTLE_REVISION="$1"
VERSION="$2"
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SONAR_DIR="$DIR/../"
DESKTOP_DIR="$SONAR_DIR/desktop"

source "$DIR"/setup-env.sh

if [[ ! -d "$DESKTOP_DIR/node_modules" ]]; then
  yarn --cwd "$DESKTOP_DIR" install --ignore-scripts --ignore-engines
fi

# if we got called with a rev argument, we got triggered from our automatic sandcastle job
if [ "$SANDCASTLE_REVISION" == "" ];
then
  OLD_VERSION=$(jq -r '.version' "$DESKTOP_DIR"/package.json)
  echo "The currently released version is $OLD_VERSION. What should the version of the next release be?"
  read -r VERSION
  yarn --cwd "$DESKTOP_DIR" version --new-version "$VERSION"
fi

echo "Preparing release $VERSION..."

# Update flipper app version to the very same version
yarn --cwd "$DESKTOP_DIR" version --new-version "$VERSION"

# Update react-native-flipper to the very same version
yarn --cwd "$SONAR_DIR"/react-native/react-native-flipper version --new-version "$VERSION" --no-git-tag-version

# Update js-flipper to the very same version
yarn --cwd "$SONAR_DIR"/js/js-flipper version --new-version "$VERSION" --no-git-tag-version

# This could be one expression with GNU sed, but I guess we want to support the BSD crap, too.
SNAPSHOT_MINOR_VERSION=$(echo "$VERSION" | sed -Ee 's/([0-9]+)\.([0-9]+)\.([0-9]+)/\3 + 1/' | bc)
SNAPSHOT_VERSION="$(echo "$VERSION" | sed -Ee 's/([0-9]+)\.([0-9]+)\.([0-9]+)/\1.\2./')""$SNAPSHOT_MINOR_VERSION""-SNAPSHOT"

echo "Bumping version number for android related files..."
# Update Android related files
"$SONAR_DIR"/scripts/bump.sh "$VERSION"

# Generate changelog
$nodejs "$DESKTOP_DIR"/scripts/generate-changelog.js

# Create commit
echo "Committing the files..."
hg addremove
hg commit -m "$(echo -e "Flipper Release: v${VERSION}\n\n\
Summary:\nReleasing version $VERSION\n\n\
Test Plan:\n\
Please follow these steps to ship the new Flipper release:\n\n\
1. Check Signal Hub for the ephemeral Flipper build. You will find instructions on how to run it in there: https://www.internalfb.com/intern/px/p/1Kcbk\n\
2. Follow the [release smoke testing checklist](https://www.internalfb.com/intern/staticdocs/flipper/docs/fb/release-infra/#release-smoke-testing) to perform some brief exploratory tests.\n\
3. If things are looking okay, accept both diffs and land them *together* as a stack.\n\
4. Once landed, the Flipper bot will comment with \"#flipperrelease with bump\" on the diff. If this doesn't happen, please do this yourself. This will kick off the [\"flipper-release\"](https://fburl.com/sandcastle/uh698xj2) job, resulting in another diff which when landed pins the new release for our users.\n\
See more details about the Flipper release process [here](https://fburl.com/flipperreleasebot).\n\n\
Reviewers: flipper\n\n\
Tags: accept2ship"
)"

# Create snapshot commit
RELEASE_REV="$(hg log -r . --template "{node}\\n")"

echo "Release commit made as $RELEASE_REV, creating new snapshot version $SNAPSHOT_VERSION..."
"$SONAR_DIR"/scripts/bump.sh --snapshot "$SNAPSHOT_VERSION"

hg commit -m "$(echo -e "Flipper Snapshot Bump: v${SNAPSHOT_VERSION}\n\n\
Summary:\nReleasing snapshot version $SNAPSHOT_VERSION\n\n\
Test Plan:\n\
No specific test action required. Please land this **together with the previous diff**.\n\
This diff is only exists to enable continuous snapshot releases on Maven. It's a Java thing. Don't think about it too much.\n\
\n\n\
Reviewers: flipper\n\n\
Tags: accept2ship"
)"

if [ "$SANDCASTLE_REVISION" == "" ];
then
  # Submit diffs, we only do this when running locally.
  # From SandcastleFlipperAutoReleaseCommand, the diffs are submitted
  # later by using the bot context
  echo "Submitting diffs for review..."
  jf submit -n -r.^::.
else
  echo "Skip submitting diffs, as this diffs should be submitted by SC"
fi


#!/usr/bin/env bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

set -e

BASEDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"
IS_SNAPSHOT="$(grep 'VERSION_NAME=[0-9\.]\+-SNAPSHOT' "$BASEDIR/gradle.properties" || echo "")"

if [ "$ANDROID_PUBLISH_KEY" == "" ]; then
  echo "No encryption key. Skipping snapshot deployment."
  exit
elif [ "$IS_SNAPSHOT" == "" ]; then
  echo "Skipping build. Given build doesn't appear to be a SNAPSHOT release."
  exit 1
else
  openssl aes-256-cbc -pbkdf2 -d -in scripts/gradle-publish-keys.enc -k "$ANDROID_PUBLISH_KEY" >> "$BASEDIR/gradle.properties"
  "$BASEDIR"/gradlew publish
fi


#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

set -e

if [ -z "$1" ]
then
    echo "Please pass the root directory of flipper repository as a first argument."
    exit 1
fi

if [ -z "$2" ]
then
    echo "Please pass the pod name to push, It just accepts 'Flipper' and 'FlipperKit', do not append podspec at the end"
    exit 1
fi

if [[ "$2" != "Flipper" ]] && [[ "$2" != "FlipperKit" ]]
then
    echo "This script just supports Flipper and FlipperKit pods. Please send either Flipper or FlipperKit as an argument."
    exit 1
fi

FLIPPER_DIR=$1
POD_NAME=$2
POD_TO_PUSH="$FLIPPER_DIR/$POD_NAME.podspec"

if ! [[ -f "$POD_TO_PUSH" ]]; then
    echo "$POD_TO_PUSH does not exist. Please check the pod name."
fi

POD_VERSION_TAG=$(< "$POD_TO_PUSH" grep "flipperkit_version =" )
POD_VERSION="${POD_VERSION_TAG##* }"
POD_VERSION=$(sed -e "s/^'//" -e "s/'$//" <<<"$POD_VERSION")

push_pods_and_retry () {
    echo "Pushing $POD_VERSION of $POD_NAME..."
    FLAGS="--use-libraries --allow-warnings --verbose --skip-import-validation"
    if [[ "$POD_NAME" == "FlipperKit" ]]
    then
        FLAGS="$FLAGS --synchronous"
    fi
    POD_COMMAND="pod trunk push $POD_TO_PUSH $FLAGS"
    MAX_ATTEMPT=4
    ATTEMPT_NUM=0
    TIME_TO_WAIT=1
    until [ "$ATTEMPT_NUM" -ge "$MAX_ATTEMPT" ]
    do
        echo "Retry attempt $ATTEMPT_NUM..."
        if [ "$ATTEMPT_NUM" -ge 1 ]
        then
        echo "Retry attempt $ATTEMPT_NUM..."
        fi
        $POD_COMMAND && break
        echo "Failed to push. Will Retry in $TIME_TO_WAIT minute."
        sleep $((60*TIME_TO_WAIT))
        # Exponential back off.
        TIME_TO_WAIT=$((2*TIME_TO_WAIT))
        ATTEMPT_NUM=$((ATTEMPT_NUM+1))
    done

    if [ "$ATTEMPT_NUM" -ge "$MAX_ATTEMPT" ]
    then
        echo "Exhausted all retry attempts and failed to push, please try again later..."
        exit 1
    fi
}

ENDPOINT_TO_CHECK="https://github.com/CocoaPods/Specs/blob/master/Specs/a/e/a/Flipper/$POD_VERSION"
if [[ "$POD_NAME" == "FlipperKit" ]]
then
    STATUS_CODE=$(curl -LI "$ENDPOINT_TO_CHECK" -o /dev/null -w '%{http_code}\n' -s)
    if ! [[ $STATUS_CODE == 200 ]]
    then
    echo "Please push $POD_VERSION of Flipper before pushing $POD_VERSION of FlipperKit."
    exit 1;
    fi
    ENDPOINT_TO_CHECK="https://github.com/CocoaPods/Specs/tree/master/Specs/3/2/5/FlipperKit/$POD_VERSION"
fi

echo "Verifying if $POD_VERSION already pushed for $POD_NAME..."
echo "Curling $ENDPOINT_TO_CHECK"
STATUS_CODE=$(curl -LI "$ENDPOINT_TO_CHECK" -o /dev/null -w '%{http_code}\n' -s)
echo "$STATUS_CODE"

if  [[ "$STATUS_CODE" -ge 400 ]]
then
    push_pods_and_retry "$@"
else
    echo "$POD_VERSION of $POD_NAME is already pushed."
    exit 0
fi

echo "Successfully published $POD_VERSION of $POD_NAME."


#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

echo "âœ¨ Creating new Sonar iOS release on GitHub..."

echo "What should the patch version of the next release be?"
read -r VERSION

TMP_DIR=$(mktemp -d)
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
JSON=$(cat "$DIR/public-ios-release.json")
JSON=${JSON/__VERSION__/$VERSION}
JSON=${JSON/__VERSION__/$VERSION}
JSON=${JSON/__USER__/$USER}
echo "$JSON" > "$TMP_DIR/job.json"
scutil create "$TMP_DIR/job.json"
echo "âœ… GitHub release will be automatically created once the Sandcastle job finishes."
rm -rf "$TMP_DIR"


#!/bin/sh
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

set -e

main () {
  local -r THIS_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
  ROOT_DIR=$(cd "$THIS_DIR" && hg root)

  source "$ROOT_DIR/xplat/js/env-utils/setup_env_vars.sh"

  export SONAR_DIR="$ROOT_DIR/xplat/sonar"
  export PATH="$SONAR_DIR/node_modules/.bin:$ROOT_DIR/xplat/third-party/node/bin:$ROOT_DIR/xplat/third-party/yarn:$PATH"
}

main


#!/bin/bash
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

set -e
if [ -z "$1" ]
  then
    echo "Please pass the root directory of flipper repository as a first argument."
    exit 1
fi

if [ -z "$2" ]
  then
    echo "Please pass the path to update the pod version in your second argument."
    exit 1
fi

darwin=false
case "$(uname)" in
  Darwin*) darwin=true ;;
esac

if ! jq --version > /dev/null; then
  if $darwin; then
    echo "jq is not installed. Installing it..."
    brew install jq
  else
    echo >&2 "jq is not installed. Please install it using your platform's package manager (apt-get, yum, pacman, etc.)."
    exit 1
  fi
fi

FLIPPER_DIR=$1
PACKAGE_VERSION=$(jq -r .version "$FLIPPER_DIR/desktop/package.json")
OLD_VERSION_POD_ARG=$(< "$2" grep "flipperkit_version =" )
OLD_VERSION="${OLD_VERSION_POD_ARG##* }"
FLIPPERKIT_VERSION_TAG='flipperkit_version'

echo "Updating $2"
if $darwin; then
sed -i '' "s/${FLIPPERKIT_VERSION_TAG} = ${OLD_VERSION}/${FLIPPERKIT_VERSION_TAG} = '${PACKAGE_VERSION}'/" "$2"
else
  sed -i "s/${FLIPPERKIT_VERSION_TAG} = ${OLD_VERSION}/${FLIPPERKIT_VERSION_TAG} = '${PACKAGE_VERSION}'/" "$2"
fi