#!/usr/bin/env bash

set -ex

echo "About to publish $GITHUB_REF to gh-pages..."

rm -rf ../gh-pages

git config --global user.name "$GIT_USER_NAME"
git config --global user.email "$GIT_USER_EMAIL"
git clone -b gh-pages --single-branch https://${GH_TOKEN_PUBLIC}@github.com/ajv-validator/ajv.git ../gh-pages
SOURCE=../gh-pages/_source
mkdir -p $SOURCE
cp *.md $SOURCE
cp -R docs $SOURCE
cp LICENSE $SOURCE
cd ../gh-pages
node ./generate

# remove logo from README
sed -E "s/<img[^>]+ajv_logo[^>]+>//" index.md > new-index.md
mv new-index.md index.md

if [[ `git status --porcelain` ]]; then
  echo "Changes detected. Updating gh-pages branch..."
  git add -A
  git commit -m "updated by ajv workflow https://github.com/ajv-validator/ajv/actions/runs/$GITHUB_RUN_ID"
  git push --quiet origin gh-pages > /dev/null 2>&1
fi

echo "Done"
