#!/bin/sh

set -e

# Update the target database snapshot with the latest targets
python ci_scripts/sync_board_database.py -vvv
git add src/mbed_tools/targets/_internal/data/board_database_snapshot.json
git add news/

# Generate API docs and add license headers to them
generate-docs --output_dir docs/api
license-files
git add docs/api

if ! NEW_VERSION=$(python ci_scripts/bump_version.py -vvv -n news/); then
    printf "Nothing to do. Exiting.\n"
    exit 0
fi

# Commit and tag new version
# Towncrier will fail if it detects a news file that has not been committed to
# the repository. So we need to ensure the news file generated by
# sync_board_database.py was committed before running towncrier.
git commit -m "Prepare mbed-tools release ${NEW_VERSION}"

# Generate changelog from news fragments
towncrier --yes --version "${NEW_VERSION}"
git add ./CHANGELOG.md

# Amend the git commit to include news file updates.
git commit --amend -C HEAD
git tag "${NEW_VERSION}"

# Push the commit and tag to the remote. Relies on `GIT_TOKEN` environment
# variable being set.
git push "https://${GIT_TOKEN}@github.com/ARMmbed/mbed-tools.git" master
git push "https://${GIT_TOKEN}@github.com/ARMmbed/mbed-tools.git" --tags
