#!/bin/bash
set -euo pipefail

BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)

# Test if all is clean.
if [ -n "$(git status --porcelain)" ]; then 
    echo "Working dir is not clean!"
    exit 1
fi
if ! [[ "$BRANCH_NAME" =~ ^master ]]; then
    echo "Not on a master branch!"
    exit 1
fi
if [[ "$(git rev-parse "$BRANCH_NAME")" != "$(git rev-parse "$(git rev-parse --abbrev-ref --symbolic-full-name @{u})")" ]]; then
    echo "branch unsynced!"
    exit 1
fi

# Make sure we have the latest info.
git pull
opam update iris-dev

echo
echo "## Updating opam file"

# Find out about auto-opam dependencies.
VERSION_REGEX='dev\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.[0-9]+\.[0-9a-f]{8}'
DEPS=$(cat opam | egrep "\"coq-[a-z0-9-]+\" *\\{ \\(= \"$VERSION_REGEX\"")

# Find latest version for each of them.
for DEP in $(echo "$DEPS" | egrep -o 'coq-[a-z0-9-]+'); do
    LATEST=$(opam show "$DEP" -f all-versions | tr -s '[:blank:]' '\n' | tail -n 1)
    echo "Latest version of $DEP is $LATEST"
    # edit opam file
    sed -E -i "s/(\"$DEP\" *\\{ \\(= )\"$VERSION_REGEX\"/\\1\"$LATEST\"/" opam
done

# See if that changed anything
if ! [ -n "$(git status --porcelain)" ]; then 
    echo "Everything up-to-date already, nothing to do!"
    exit 0
fi

echo
echo "## Testing opam file"

# Test if this is installable.
# Of course, this being opam, doing the test is quite annoying: we have to ensure that opam
# actually reads the updated deps file.
make build-dep/opam
opam update --development -y
if ! make build-dep OPAMFLAGS="--dry-run -y"; then
    echo "opam failed, dependencies are likely bogus"
    exit 1
fi

# Create a commit.
echo
git commit -am "update dependencies"
git show

# Ask user to push
read -p "Do you want me to push this change? (y/N) " ANSWER
if [[ "$ANSWER" == y* ]]; then
    git push
fi
