#!/bin/bash -e
set -o pipefail

asset_urls="$@"

git checkout gh-pages
cd charts

# Download chart(s) from release assets
for asset_url in $asset_urls; do
    if ! echo "$asset_url" | grep -q 'chart.*tgz$'; then
        echo "Skipping $asset_url, does not look like a Helm chart archive"
        continue
    fi

    echo "Downloading $asset_url..."
    curl -sSfLO $asset_url
    # We rely on all release assets having the same baseurl
    download_baseurl=`dirname $asset_url`
done

if [ -z "$download_baseurl" ]; then
    echo "No Helm chart release assets found"
    exit 0
fi

echo "Updating helm index"
helm repo index . --merge index.yaml --url $download_baseurl

# Check if there were any changes in the repo
if [ -z "`git status --short`" ]; then
    echo "No changes in Helm repo incex, gh-pages branch already up-to-date"
    exit 0
fi

# Create a new commit
commit_msg="Update Helm repo index for release `basename $download_baseurl`

Auto-generated by `basename $0`"

echo "Committing changes..."
git commit -m "$commit_msg" -- index.yaml

echo "gh-pages branch successfully updated"
