#!/bin/bash

RESTRICT_REPOSITORY="dials/data"
if [[ "${TRAVIS_REPO_SLUG}" != "${RESTRICT_REPOSITORY}" ]]; then
  echo Skipping step outside of ${RESTRICT_REPOSITORY} repository
  exit 0
fi

git config --global user.name "Travis CI on github.com/dials/data"
git config --global user.email "dials@noreply.github.com"
git config credential.helper "store --file=.git/credentials"
echo "https://${GITHUB_TOKEN}:@github.com" > .git/credentials

if [[ "${TRAVIS_BRANCH}" == "master" ]] && [[ "${TRAVIS_PULL_REQUEST}" == "false" ]]; then
  echo Installing github cli
  pushd .. >/dev/null
  wget -nv https://github.com/github/hub/releases/download/v2.6.0/hub-linux-amd64-2.6.0.tgz -O - | tar xz || exit 1
  export PATH=$(pwd)/hub-linux-amd64-2.6.0/bin/:${PATH}
  popd >/dev/null
  hub --version || exit 1

  echo Open pull requests:
  declare -A UPDATEBRANCHES
  for BRANCH in $(hub pr list -b master -f '%H%n'); do
    echo ${BRANCH}
    UPDATEBRANCHES[${BRANCH}]=1
  done
  echo

  echo Installing package outside tox environment
  pip install -e .

  echo Checking for required definition updates...
  for DATASET in $(python -c "import dials_data.datasets as ddd; print('\n'.join(ddd.fileinfo_dirty))")
  do
    echo Checking ${DATASET}
    [ ${UPDATEBRANCHES[update-${DATASET}]+x} ] || {
      echo create/update branch ${DATASET}
      git checkout -b "update-${DATASET}"
      git reset --hard master
      git commit --allow-empty -m "Trigger update of dataset ${DATASET}"
      git push -f -u origin "update-${DATASET}"
      echo create pull request
      hub pull-request -f -m "Update dataset ${DATASET}"
    }
  done
fi

if [[ ${TRAVIS_BRANCH} == update-* ]] && [[ "${TRAVIS_PULL_REQUEST}" == "false" ]]; then
  git checkout "${TRAVIS_BRANCH}"
  CANDIDATE=$(echo ${TRAVIS_BRANCH} | cut -c 8-)
  if [[ ! -z $CANDIDATE ]]; then
    echo Installing package outside tox environment
    pip install -e .

    echo Considering updating information on dataset ${CANDIDATE}
    for DATASET in $(dials.data list --quiet --missing-hashinfo)
    do
      if [[ "${DATASET}" == "${CANDIDATE}" ]]; then
        echo Updating dataset ${DATASET}
        dials.data get --create-hashinfo ${DATASET} || exit 1
        mv ${DATASET}.yml dials_data/hashinfo/${DATASET}.yml || exit 1
        if [ -z "$(git status --porcelain)" ]; then
          echo Working directory remained clean. Something went wrong.
          exit 1
        fi
        git add dials_data/hashinfo/${DATASET}.yml || exit 1
        echo Committing update
        git commit -m "Update file information for dataset ${DATASET}" || exit 1
        # Ensure dataset will not be downloaded again in the next round
        dials.data list --quiet --missing-hashinfo | tee remaining-datasets || exit 1
        grep -- "^${DATASET}$" < remaining-datasets && {
          echo Hashinfo sanity check failed
          exit 1
        }
        git push || exit 1
        echo Success.
        break
      fi
    done
  fi
fi
