#!/usr/bin/env bash

# Copyright 2018-2019 Datawire. All rights reserved.
#
# 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 -o errexit

source_dir=$(pwd)

if [ -z "$NETLIFY_AUTH_TOKEN" ]; then
    NETLIFY_AUTH_TOKEN=$(keybase fs read /keybase/team/datawireio/secrets/netlify.lukeshu.personal-access-token)
fi

if [ -z "$WEBSITE_BRANCH" ]; then
    WEBSITE_BRANCH="master"
fi

if [ -z "$WEBSITE_DIR" ]; then
    WEBSITE_DIR="/tmp/getambassador.io-$WEBSITE_BRANCH"
fi

if [ ! -d "$WEBSITE_DIR" ]; then 
	echo "$WEBSITE_DIR doesn't exist: did you run doc-setup?" >&2
	exit 1
fi

set -o nounset
set -o xtrace

cd "$WEBSITE_DIR"
npm run build

# From ./ambassador/.ci/publish-website-preview master

if ! [[ -d /tmp/getambassador.io-${WEBSITE_BRANCH}/public ]]; then
	echo '[publish-website-preview] skipping: website preview was not built'
	exit 0
fi

npm install netlify-cli -g

netlify deploy \
	--dir="/tmp/getambassador.io-${WEBSITE_BRANCH}/public" \
	--message="ambassador.git preview $WEBSITE_BRANCH from $USER" \
	--site=1d6f5395-6386-49af-8b47-e85aa28488f8 \
	--auth="${NETLIFY_AUTH_TOKEN}" \
	--json \
	> /tmp/netlify-deploy.json

cat /tmp/netlify-deploy.json

# If you look in publish-website-preview, you'll see it post status to GitHub. Skip that
# since we're not running inside Travis.

# Install the broken link checker...

${source_dir}/.ci/install-blc

# ...then continue with stuff from blc-website-preview

set -o verbose

pushd "/tmp/getambassador.io-$WEBSITE_BRANCH/public"
python3 -m http.server 2>/dev/null &
trap "kill $!" EXIT
popd

cd /tmp/getambassador.io-blc
./blc.js http://localhost:8000/ > /tmp/blc.txt

set +o verbose
num_complaints=$(grep ^Page /tmp/blc.txt | sort -u | wc -l)
RED=$'\033[1;31m'
GRN=$'\033[1;32m'
BLD=$'\033[1m'
END=$'\033[0m'
if [[ $num_complaints -eq 0 ]]; then
	printf "%s======================= 0 broken-link-checker complaints for %s =======================%s\n" "$GRN$BLD" "$WEBSITE_BRANCH" "$END"
else
	printf "%s======================= %d broken-link-checker complaints for %s ======================%s\n" "$RED$BLD" $num_complaints "$WEBSITE_BRANCH" "$END"
	grep ^Page /tmp/blc.txt | sort -u
	printf "%s====================== end broken-link-checker complaints for %s ======================%s\n" "$RED$BLD" "$WEBSITE_BRANCH" "$END"
	exit $num_complaints
fi

# Don't post to GitHub.
