#!/bin/bash

# Copyright 2019 The Kubernetes Authors.
#
# 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
set -o nounset
set -o pipefail

KUBE_ROOT=$(dirname "${BASH_SOURCE[0]}")/../..
cd "${KUBE_ROOT}" || exit 1

os=$(go env GOOS)
arch=$(go env GOARCH)

MDBOOK_VERSION="0.4.25"

# translate arch to rust's conventions (if we can)
if [[ ${arch} == "amd64" ]]; then
    arch="x86_64"
elif [[ ${arch} == "x86" ]]; then
    arch="i686"
fi

# translate os to rust's conventions (if we can)
ext="tar.gz"
cmd="tar -C /tmp -xzvf"
case ${os} in
    windows)
        target="pc-windows-msvc"
        ext="zip"
        cmd="unzip -d /tmp"
        ;;
    darwin)
        target="apple-darwin"
        # only x86_64 is published for darwin
        arch="x86_64"
        ;;
    linux)
        # works for linux, too
        target="unknown-${os}-gnu"
        ;;
    *)
        target="unknown-${os}"
        ;;
esac

# grab mdbook
# we hardcode linux/amd64 since rust uses a different naming scheme and it's a pain to tran
echo "downloading mdBook-v${MDBOOK_VERSION}-${arch}-${target}.${ext}"
set -x
curl -sL -o /tmp/mdbook.${ext} "https://github.com/rust-lang-nursery/mdBook/releases/download/v${MDBOOK_VERSION}/mdBook-v${MDBOOK_VERSION}-${arch}-${target}.${ext}"
${cmd} /tmp/mdbook.${ext}
chmod +x /tmp/mdbook

# Finally build the book.
(cd docs/book && /tmp/mdbook build)
