#!/bin/bash
# Copyright 2019 Sebastian Wiesnser <sebastian@swsnr.de>

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

next_version="$1"
if [[ -z "${next_version}" ]]; then
    echo "Next version missing; aborting"
    exit 1
fi

changes="$(git status --porcelain)"
if [[ -n "${changes}" ]]; then
    git status
    echo "Working directory not clean; aborting"
    exit 1
fi

if [[ "$(git symbolic-ref --short HEAD)" != "master" ]]; then
    echo "Not on master branch; aborting"
    exit 1
fi

ci_status="$(curl -sfS -H 'Accept: application/vnd.github.antiope-preview+json' \
    "https://api.github.com/repos/lunaryorn/gethostname.rs/commits/$(git rev-parse HEAD)/check-suites" |
    jq -r '.check_suites | map(.status) | join("\n")')"
if [[ "${ci_status}" != "completed" ]]; then
    echo "CI for HEAD pending or failed (${ci_status}); aborting"
    exit 1
fi

latest_version="$(git tag --sort '-v:refname' | grep '^gethostname-' | head -n1 | cut -d'-' -f2)"

# Substitute version in Cargo.toml and add it to Git; we ignore Cargo.lock here
# since it's being git-ignored.
sed -i '' "1,/^version =/ s/^version = .*$/version = \"$next_version\"/" Cargo.toml
git add Cargo.toml

# Update the changelog:
# 1. Append a headline for the current version right after [Unreleased] headline
# 2. Append link references for the new version and the new unreleased version
# 3. Delete the old link reference for the Unreleased header
sed -e "/^## \[Unreleased\]\$/ a\\
\\
## [${next_version}] – $(date +%Y-%m-%d)\\" \
    -e "\$a\\
[$next_version]: https://github.com/lunaryorn/gethostname.rs/compare/gethostname-${latest_version}...gethostname-${next_version}\\
[Unreleased]: https://github.com/lunaryorn/gethostname.rs/compare/gethostname-${next_version}...HEAD" \
    -e '/^\[Unreleased\]:/ D' \
    -i '' CHANGELOG.md
git add CHANGELOG.md

git commit -m "Release $next_version"
git tag -m "gethostname $next_version" "gethostname-$next_version"
cargo publish --no-verify
git push --follow-tags origin master

