set -e

# The scala/scala checkout directory (set by Jenkins, or `/home/travis/build/scala/scala` on travis)
WORKSPACE="${WORKSPACE-`pwd`}"

# On Jenkins, each job needs its own ivy2 cache to avoid conflicts between jobs. On travis, it's ~/.ivy2.
if [ "$TRAVIS" = "true" ]; then
  IVY2_DIR="$HOME/.ivy2"
else
  IVY2_DIR="$WORKSPACE/.ivy2"
fi

# used by `sbtResolve`
rm -rf "$WORKSPACE/resolutionScratch_"
mkdir -p "$WORKSPACE/resolutionScratch_"

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

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

# only used on jenkins
sbtRepositoryConfig="$WORKSPACE/scripts/sbt-repositories-config"
addIntegrationResolver="set resolvers in Global += \"scala-pr\" at \"$integrationRepoUrl\""

jcenterCacheUrl=${jcenterCacheUrl-"https://scala-ci.typesafe.com/artifactory/jcenter/"}

# used by `checkAvailability`
TMP_ROOT_DIR=$(mktemp -d -t pr-scala.XXXX)
TMP_DIR="${TMP_ROOT_DIR}/tmp"
mkdir "${TMP_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 http://www.scala-sbt.org/0.13/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
  jcenter-cache: $jcenterCacheUrl
  local
  maven-central
  typesafe-ivy-releases-boot: https://repo.lightbend.com/typesafe/ivy-releases/, [organisation]/[module]/[revision]/[type]s/[artifact](-[classifier]).[ext], bootOnly
  typesafe-ivy-releases: https://dl.bintray.com/typesafe/ivy-releases/, [organisation]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[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
}


# https://github.com/travis-ci/docs-travis-ci-com/issues/949
travis_fold_start() {
  echo ""
  echo -e "travis_fold:start:$1\033[33;1m$2\033[0m"
}

travis_fold_end() {
  echo -e "\ntravis_fold:end:$1\r"
  echo ""
}


##### git
gfxd() {
  git clean -fxd # TESTING
}

update() {
  [[ -d $WORKSPACE ]] || mkdir -p $WORKSPACE
  cd $WORKSPACE

  if [ ! -d $WORKSPACE/$2 ]; then git clone "https://github.com/$1/$2.git"; fi

  cd $2

  git fetch --tags "https://github.com/$1/$2.git"
  (git fetch "https://github.com/$1/$2.git" $3 && git checkout -fq FETCH_HEAD) #|| git checkout -fq $3 # || fallback is for local testing on tag
  git reset --hard
}

##### sonatype interface

st_curl(){
  curl -H "Content-Type: application/json" -H "accept: application/json,application/vnd.siesta-error-v1+json,application/vnd.siesta-validation-errors-v1+json"  -K ~/.sonatype-curl -s -o - $@
}

st_stagingReposOpen() {
 st_curl "$stApi/staging/profile_repositories" | jq '.data[] | select(.profileName == "org.scala-lang") | select(.type == "open")'
}

st_stagingRepoDrop() {
  repo=$1
  message=$2
  echo "{\"data\":{\"description\":\"$message\",\"stagedRepositoryIds\":[\"$repo\"]}}" | st_curl -X POST -d @- "$stApi/staging/bulk/drop"
}

st_stagingRepoClose() {
  repo=$1
  message=$2
  echo "{\"data\":{\"description\":\"$message\",\"stagedRepositoryIds\":[\"$repo\"]}}" | st_curl -X POST -d @- "$stApi/staging/bulk/close"
}

#### sbt tools

sbtBuild() {
  travis_fold_start build "Building $(basename $PWD) with $@"
  $SBT_CMD -no-colors $sbtArgs 'set scalacOptions += "-Xfatal-warnings:false"' "$addIntegrationResolver" "${scalaVersionTasks[@]}" "${publishTasks[@]}" "$@"
  travis_fold_end build
}

sbtResolve() {
  cd "$WORKSPACE/resolutionScratch_"
  touch build.sbt
  # Can be set to `full` if a module requires cross-versioning against the full Scala version, like the continuations plugin used to.
  cross=${4-binary}
  # echo "### sbtResolve: $SBT_CMD -no-colors $sbtArgs " "${scalaVersionTasks[@]}" "\"$1\" % \"$2\" % \"$3\" cross CrossVersion.$cross"
  travis_fold_start resolve "Resolving \"$1\" % \"$2\" % \"$3\" cross CrossVersion.$cross"
  $SBT_CMD -no-colors $sbtArgs "${scalaVersionTasks[@]}" \
    "$addIntegrationResolver" \
    "set libraryDependencies := Seq(\"$1\" % \"$2\" % \"$3\" cross CrossVersion.$cross)" \
    "show update"
  res=$?
  cd $WORKSPACE
  travis_fold_end resolve
  return $res
}

clearIvyCache() {
  travis_fold_start clearIvy "Clearing ivy cache"
  rm -fv $IVY2_DIR/exclude_classifiers $IVY2_DIR/exclude_classifiers.lock
  rm -rfv $IVY2_DIR/cache/org.scala-lang $IVY2_DIR/cache/org.scala-lang.modules
  rm -rfv $IVY2_DIR/local/org.scala-lang $IVY2_DIR/local/org.scala-lang.modules
  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
  travis_fold_end clearIvy
}

#### travis

triggerScalaDist() {
  local jsonTemplate='{ "request": { "branch": "%s", "message": "Scala Dist %s", "config": { "before_install": "export version=%s mode=release scala_sha=%s" } } }'
  local json=$(printf "$jsonTemplate" "$TRAVIS_BRANCH" "$SCALA_VER" "$SCALA_VER" "$TRAVIS_COMMIT")

  local curlStatus=$(curl \
    -s -o /dev/null -w "%{http_code}" \
    -H "Travis-API-Version: 3" \
    -H "Authorization: token $TRAVIS_TOKEN" \
    -H "Content-Type: application/json" \
    -d "$json" \
    https://api.travis-ci.org/repo/scala%2Fscala-dist/requests)

  [[ "$curlStatus" == "202" ]] || {
    echo "failed to start job"
    exit 1
  }
}
