1#!/usr/bin/env bash
2
3# Abort on first error
4set -e
5
6# Directories
7SITE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
8ROOT_DIR="$SITE_DIR/.."
9BUILD_DIR="$SITE_DIR/build"
10DIST_DIR="$BUILD_DIR/dist"
11PAGES_DIR="$BUILD_DIR/pages"
12
13# Init options
14GRADLE_OPT=
15PUSH_OPT=
16
17# Set dry run if needed
18if [ "$2" == "push" ] ; then
19    echo "--- Doing LIVE site deployment, so do clean build"
20    GRADLE_OPT=clean
21else
22    echo "--- Doing dry-run. To commit do 'deploy.sh <version> push'"
23    PUSH_OPT=--dry-run
24fi
25
26# Makes sure that site is built
27"$ROOT_DIR/gradlew" $GRADLE_OPT site
28
29# Cleanup dist directory (and ignore errors)
30rm -rf "$PAGES_DIR" || true
31
32# Prune worktrees to avoid errors from previous attempts
33git --work-tree "$ROOT_DIR" worktree prune
34
35# Create git worktree for gh-pages branch
36git --work-tree "$ROOT_DIR" worktree add -B gh-pages "$PAGES_DIR" origin/gh-pages
37
38# Now work in newly created workspace
39cd "$PAGES_DIR"
40
41# Fixup all the old documentation files
42# Remove non-.html files
43git rm `find . -type f -not -name '*.html' -not -name '.git'` > /dev/null
44
45# Replace "experimental" .html files with links to the corresponding non-experimental version
46# or remove them if there is no corresponding non-experimental file
47echo "Redirecting experimental pages"
48git_add=()
49git_rm=()
50for file in `find . -type f -name '*.html'` ; do
51    match=nothing_is_found
52    if [[ $file =~ \.experimental ]] ; then
53        match="${file//\.experimental/}"
54    fi
55    if [[ -f "$DIST_DIR/$match" ]] ; then
56        # redirect to non-experimental version
57        echo "<html><script>window.onload = function() { window.location.href = \"/kotlinx.coroutines${match#.}\" }</script></html>" > "$file"
58        git_add+=("$file")
59    else
60        # redirect not found -- remove the file
61        git_rm+=("$file")
62    fi
63done
64git add "${git_add[@]}"
65git rm "${git_rm[@]}" > /dev/null
66
67# Copy new documentation from dist
68cp -r "$DIST_DIR"/* "$PAGES_DIR"
69
70# Add it all to git
71git add *
72
73# Commit docs for the new version
74if [ -z "$1" ] ; then
75    echo "No argument with version supplied -- skipping commit"
76else
77    git commit -m "Version $1 docs"
78    git push $PUSH_OPT origin gh-pages:gh-pages
79fi
80