#!/bin/bash
set -euo pipefail

# (c) 2018-2024 Symfony SAS
# All Rights Reserved

echo "// Installing Symfony tools //"

# Rely on .gitattributes to get the current tag if possible
TAG=$( (grep -o ', tag: [^,]*' <<'EOT' || echo '') | head -n1 | cut -b8-
, $Format:%D$
EOT
)
# Fallback to reading the tag using git (useful when deploying from the local dev env)
GIT_DIR="$( dirname -- "$( readlink -f -- "$0"; )" )/.git"
TAG=${TAG:-$( ([ -d "$GIT_DIR" ] && git --git-dir="$GIT_DIR" log --pretty=format:', %D' -n 1 | grep -o ', tag: [^,]*' || echo '') | head -n1 | cut -b8- )}

SC_CHANNEL="${SC_CHANNEL:-$TAG}"

# Download the tools
CACHE_DIR=${SYMFONY_CACHE_DIR:-${PLATFORM_CACHE_DIR:-/tmp/$USER/cache}}
mkdir -p "$PLATFORM_APP_DIR/.global/bin/" "$CACHE_DIR" "$PLATFORM_APP_DIR/.global/lib/"
(cd "${CACHE_DIR}" && curl -fLOsz tools.tar.bz2 "https://get.symfony.com/cloud/${SC_CHANNEL:-stable}/tools.tar.bz2") 2>/dev/null
tar -C "$PLATFORM_APP_DIR/.global/bin/" -jxpf "$CACHE_DIR/tools.tar.bz2"
if [ -d "/nix/" ]; then
    rm -f /app/.global/bin/composer /app/.global/bin/composer2 /app/.global/bin/composer1
    ln -sf /usr/bin/composer /app/.global/bin/composer
else
    ln -sf /app/.global/bin/composer2 /app/.global/bin/composer
fi

# Please, don't remove this line (or call it yourself if you tweak the Symfony integration)
# as this is how Symfony gets some money from Platform.sh
symfony-log

if ! command -v platform >/dev/null ; then
    echo "// Installing cloud CLI //"
    (curl -fLsS https://platform.sh/cli/installer | php -n -d"$(php -n -r 'extension_loaded("json")||print("extension");')"=json.so -d extension=phar.so -d extension=mbstring.so -d extension=posix.so -d extension=curl.so) >/dev/null 2>&1 || true
fi

cat >> "$PLATFORM_APP_DIR/.global/environment" <<EOS
export PLATFORMSH_CLI_APPLICATION_TMP_SUB_DIR=platformsh-cli-\${USER:-tmp}
export PATH=\$PLATFORM_APP_DIR/bin:\$PLATFORM_APP_DIR/vendor/bin:\$PATH \$(symfony var:export)
export PLATFORM_APP_COMMAND="symfony-pre-start; \${PLATFORM_APP_COMMAND:-}"
if [ "\${PLATFORM_ENVIRONMENT_TYPE:-}" = "production" ]; then
    export APP_RUNTIME_ENV=\${APP_RUNTIME_ENV:-prod}
fi
EOS
