#!/bin/bash

set -e

CURRENT_VERSION=v0.3.1

get_latest_release() {
  curl --silent "https://api.github.com/repos/algolia/magento2-tools/releases/latest" | # Get latest release from GitHub api
    grep '"tag_name":' |                                            # Get tag line
    sed -E 's/.*"([^"]+)".*/\1/'                                    # Pluck JSON value
}

LATEST_VERSION="$(get_latest_release)"

echo "Current version: " "$CURRENT_VERSION"
echo "Latest version: " "$LATEST_VERSION"

if [ "$LATEST_VERSION" != "$CURRENT_VERSION" ]
then
    echo "Updating to latest version..."
    composer global remove algolia/magento2-tools && composer global require algolia/magento2-tools && echo "Latest vesion is now installed, please re-run the command again."
    exit 1
fi
