#!/bin/bash
set -e

PORT=9001
IMAGE=rancher/docs
TAG=dev
THEME=
BUILD_BUILD=
BUILD_DEV=
SKIP_PULL=
UPLOAD=

# cd to app root
CWD=$(dirname $0)
if [[ `basename $(pwd)` = 'scripts' ]]; then
  cd ../
else
  cd `dirname $CWD`
fi

print_help()
{
  cat 1>&2 <<EOF
Usage:

[-b | -d] [-p PORT] [-s] [-t DIR] [-u]

-b      - Build the build & dev images instead of pulling from the registry
-d      - Build the dev image instead of pulling from the registry
-p PORT - Port to listen on
-s      - Skip pulling build/dev images
-t DIR  - Use DIR to for the theme, to devlop the theme at the same time
-u      - Upload/push the build image after building

EOF
}

echoerr()
{
  printf "%s\n" "$*" >&2;
}

absolute() {
# $1 : relative filename
  echo "$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
}


while getopts ":bdp:st:u" opt;do
  case $opt in
  b)
    BUILD_BUILD="true"
    BUILD_DEV="true"
    ;;
  d)
    BUILD_DEV="true"
    ;;
  p)
    PORT="${OPTARG}"
    ;;
  s)
    SKIP_PULL="true"
    ;;
  t)
    THEME="${OPTARG}"
    ;;
  u)
    UPLOAD="true"
    ;;
  \?)
    echoerr "Invalid arguments"
    print_help
    exit 1
    ;;
  :)
    echoerr "Option -${OPTARG} requires an argument."
    print_help
    exit 1
    ;;
  esac
done

THEMEVOLUME=""
if [[ "$THEME" ]]; then
  echo "Using theme from ${THEME}"
  ABSOLUTE=$(absolute $THEME)
  THEMEVOLUME="-v ${ABSOLUTE}:/run/node_modules/rancher-website-theme"
fi

if [[ "$BUILD_BUILD" ]]; then
  echo "Building ${IMAGE}:build"
  docker build --no-cache -f Dockerfile.build --build-arg TWITTER_CONSUMER=${TWITTER_CONSUMER} --build-arg TWITTER_SECRET=${TWITTER_SECRET} -t ${IMAGE}:build .
  if [[ "$UPLOAD" ]]; then
  docker push ${IMAGE}:build
  fi
elif [[ "$SKIP_PULL" ]]; then
  echo "Skipping pull of ${IMAGE}:build"
else
  echo "Pulling ${IMAGE}:build"
  docker pull ${IMAGE}:build
fi

if [[ "$BUILD_DEV" ]]; then
  TAG=local
  echo "Building ${IMAGE}:${TAG}"
  docker build -f Dockerfile.dev -t ${IMAGE}:${TAG} .
elif [[ "$SKIP_PULL" ]]; then
  echo "Skipping pull of ${IMAGE}:${TAG}"
else
  echo "Pulling ${IMAGE}:${TAG}"
  docker pull ${IMAGE}:${TAG}
fi

echo "Starting server on http://localhost:${PORT}"
docker run --rm -p ${PORT}:${PORT} -it \
  -v $(pwd)/archetypes:/run/archetypes \
  -v $(pwd)/assets:/run/assets \
  -v $(pwd)/content:/run/content \
  -v $(pwd)/data:/run/data \
  -v $(pwd)/layouts:/run/layouts \
  -v $(pwd)/scripts:/run/scripts \
  -v $(pwd)/static:/run/static \
  -v $(pwd)/.git:/run/.git \
  -v $(pwd)/config.toml:/run/config.toml \
  ${THEMEVOLUME} ${IMAGE}:${TAG} --port=${PORT}
