#!/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

if [ -z "$NETLIFY_SITE" ]; then
    NETLIFY_SITE=28e95687-926a-4528-9a93-b579892f9586
fi

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

RED=$'\033[1;31m'
GRN=$'\033[1;32m'
BLD=$'\033[1m'
END=$'\033[0m'

PROD=""

if [ "$1" == "--prod" ]; then
    echo "PROD MODE"
    PROD="--prod"
    shift
fi

source_dir=$(pwd)

if [ \( $(basename $source_dir) != "ambassador" \) -a \( -d "$source_dir/ambassador/docs" \) ]; then
    source_dir="$source_dir/ambassador"
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"

printf "${GRN}${BLD}==== Starting build${END}\n"

yarn run build

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

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

npm install netlify-cli

printf "${GRN}${BLD}==== Deploying to Netlify${END}\n"

netlify deploy \
	--dir="${WEBSITE_DIR}/public" \
	--message="ambassador.git preview $WEBSITE_BRANCH from $USER" \
	--site="${NETLIFY_SITE}" \
	--auth="${NETLIFY_AUTH_TOKEN}" \
	--json \
    $PROD \
	> /tmp/netlify-deploy.json

# cat /tmp/netlify-deploy.json

# Yep. This is ugly.
DEPLOY_URL=$(python3 -c "import json; import sys; x=json.load(sys.stdin); print(x['deploy_url'])" < /tmp/netlify-deploy.json)
printf "${GRN}${BLD}==== Deployed to ${END}${DEPLOY_URL}\n"

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

printf "${GRN}${BLD}==== Installing BLC${END}\n"

# Install and run the broken link checker...

printf "${GRN}${BLD}==== Running BLC${END}\n"

export WEBSITE_DIR
export GH_TOKEN='' # Don't post to GitHub; set an exit code instead
${source_dir}/.ci/website-preview-blc

printf "${GRN}${BLD}==== Deployed to ${END}${DEPLOY_URL}\n"
