#!/usr/bin/env bash

# bump_version - increase the shared version and generate changelogs

set -o errexit
set -o pipefail
set -o xtrace

usage() {
    echo -e "bump_version - increase the shared version"
    echo -e ""
    echo -e "Usage:"
    echo -e " $ bump_version <new_version>"
}

if [[ -z $1 ]]; then
    usage
    exit 1
fi

shared_version_file="./SharedVersion.cs"
# csproj files for nuget packages
jellyfin_subprojects=(
  MediaBrowser.Common/MediaBrowser.Common.csproj
  Jellyfin.Data/Jellyfin.Data.csproj
  MediaBrowser.Controller/MediaBrowser.Controller.csproj
  MediaBrowser.Model/MediaBrowser.Model.csproj
  Emby.Naming/Emby.Naming.csproj
  src/Jellyfin.Extensions/Jellyfin.Extensions.csproj
)
issue_template_file="./.github/ISSUE_TEMPLATE/issue report.yml"

new_version="$1"
new_version_sed="$( cut -f1 -d'-' <<<"${new_version}" )"

old_version="$(
    grep "AssemblyVersion" ${shared_version_file} \
        | sed -E 's/\[assembly: ?AssemblyVersion\("([0-9\.]+)"\)\]/\1/'
)"
echo old assembly version: $old_version

# Set the assembly version to the specified new_version
sed -i "s|${old_version}|${new_version_sed}|g" ${shared_version_file}

# update nuget package version
for subproject in ${jellyfin_subprojects[@]}; do
    echo ${subproject}
    # Parse the version from the *.csproj file
    old_version="$(
        grep "VersionPrefix" ${subproject} \
            | awk '{$1=$1};1' \
            | sed -E 's/<VersionPrefix>([0-9\.]+[-a-z0-9]*)<\/VersionPrefix>/\1/'
    )"
    echo old nuget version: $old_version

    # Set the nuget version to the specified new_version
    sed -i "s|${old_version}|${new_version_sed}|g" ${subproject}
done

# Set the version in the GitHub issue template file
sed -i "s|${old_version}|${new_version_sed}|g" ${issue_template_file}

# Stage the changed files for commit
git add .
git status -v
