set -e

# The scala/scala checkout directory (set by Jenkins, or the current directory on GitHub Actions)
WORKSPACE="${WORKSPACE-`pwd`}"

IVY2_DIR="$HOME/.ivy2"

SBT_VERSION=`grep sbt.version $WORKSPACE/project/build.properties | sed -n 's/sbt.version=\(.*\)/\1/p'`

SBT_CMD=${SBT_CMD-sbt}
SBT_CMD="$SBT_CMD -sbt-version $SBT_VERSION"

# repo to publish builds
integrationRepoUrl=${integrationRepoUrl-"https://scala-ci.typesafe.com/artifactory/scala-integration/"}

# only used on jenkins
sbtRepositoryConfig="$WORKSPACE/scripts/sbt-repositories-config"

# used by `checkAvailability`
TMP_ROOT_DIR=$(mktemp -d -t pr-scala.XXXX)
TMP_DIR="${TMP_ROOT_DIR}/tmp"
mkdir "${TMP_DIR}"

# Used for publishing starr and locker
BOOTSTRAP_REPO_DIR="${TMP_ROOT_DIR}/bootstrap-repo"
mkdir "${BOOTSTRAP_REPO_DIR}"

addIntegrationResolver="set resolvers in Global += \"scala-pr\" at \"$integrationRepoUrl\""
addBootstrapResolver="set resolvers in Global += \"scala-bootstrap\" at \"file://$BOOTSTRAP_REPO_DIR\""

# General debug logging
# $* - message
function debug () {
  echo "----- $*"
}

function parseScalaProperties(){
  propFile="$WORKSPACE/$1"
  if [ ! -f $propFile ]; then
    echo "Property file $propFile not found."
    exit 1
  else
    awk -f "scripts/readproperties.awk" "$propFile" > "$propFile.sh"
    . "$propFile.sh" # yeah yeah, not that secure, improvements welcome (I tried, but bash made me cry again)
  fi
}


## TAKEN FROM UBER-BUILD, except that it "returns" (via $RES) true/false
# Check if an artifact is available
# $1 - groupId
# $2 - artifacId
# $3 - version
# $4 - extra repository to look in (optional)
# return value in $RES
function checkAvailability () {
  pushd "${TMP_DIR}"
  rm -rf *
  set +e
  mvn -q "${MAVEN_ARGS[@]}" -DremoteRepositories="$4" -DgroupId="$1" -DartifactId="$2" -Dversion="$3" -Dtransitive=false dependency:get
  RES=$?
  set -e

# log the result
  if [ ${RES} == 0 ]
  then
    debug "$1:$2:jar:$3 found !"
    RES=true
  else
    debug "$1:$2:jar:$3 not found !"
    RES=false
  fi
  popd
}

# Only used on Jenkins
# Generate a repositories file with all allowed repositories in our build environment.
# Takes a variable number of additional repositories as argument.
# See https://www.scala-sbt.org/1.x/docs/Proxy-Repositories.html
function generateRepositoriesConfig() {
  echo > "$sbtRepositoryConfig" '[repositories]'
  if [[ $# -gt 0 ]]; then
    for i in $(seq 1 $#); do
      echo >> "$sbtRepositoryConfig" "  script-repo-$i: ${!i}"
    done
  fi

  cat >> "$sbtRepositoryConfig" << EOF
  local
  maven-central
  typesafe-ivy-releases: https://repo.lightbend.com/typesafe/ivy-releases/, [organisation]/[module]/[revision]/[type]s/[artifact](-[classifier]).[ext]
  sbt-plugin-releases: https://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/, [organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext]
EOF
}


# Collapsible sections in the GitHub Actions log; they can't be nested
fold_start() {
  echo "::group::$2"
}

fold_end() {
  # sbt's output can end without a newline, and the marker only counts at the start of a line
  echo
  echo "::endgroup::"
}


#### sbt tools

clearIvyCache() {
  fold_start clearIvy "Clearing ivy cache"
  rm -fv $IVY2_DIR/exclude_classifiers $IVY2_DIR/exclude_classifiers.lock
  if [ -d $IVY2_DIR ]; then find $IVY2_DIR -name "*compiler-interface*$SCALA_VER*" | xargs rm -rfv; fi
  if [ -d $HOME/.sbt ]; then find $HOME/.sbt -name "*compiler-interface*$SCALA_VER*" | xargs rm -rfv; fi
  fold_end clearIvy
}

#### scala-dist

# Builds the distribution packages for a nightly in scala-dist's workflow, without uploading them
triggerScalaDist() {
  if [ "$publishToSonatype" = "yes" ]; then
    echo "Not triggering scala-dist: after sonatype migration to central repository, staged (but unreleased) builds are not available through any resolver."
  else
    local jsonTemplate='{ "ref": "%s", "inputs": { "version": "%s", "scala_sha": "%s", "mode": "release" } }'
    local json=$(printf "$jsonTemplate" "$GITHUB_REF_NAME" "$SCALA_VER" "$GITHUB_SHA")

    # the response body, followed by the HTTP status on its own line
    local response=$(curl \
      -s -w "\n%{http_code}" \
      -H "Accept: application/vnd.github+json" \
      -H "Authorization: Bearer $SCALA_REPO_TOKEN" \
      -d "$json" \
      https://api.github.com/repos/scala/scala-dist/actions/workflows/dist.yml/dispatches)
    local curlStatus=${response##*$'\n'}

    [[ "$curlStatus" == "204" ]] || {
      echo "failed to start scala-dist's workflow: HTTP $curlStatus"
      echo "${response%$'\n'*}"
      exit 1
    }
  fi
}
