#!/bin/bash
RED='\033[0;31m'
NO_COLOR='\033[0m'
set -u

export APP_HOSTNAME
export GITHUB_API_URL
export GITHUB_WEB_URL
export GITHUB_CLIENT_ID
export GITHUB_CLIENT_SECRET
export SSL_CERT_FILE
export GITHUB_APP_ID
export GITHUB_APP_URL

no_install_deps() {
  local file="/src/components/${1}/cleanup"
  if [ ! -f $file ]; then
    touch $file
  else
    echo "1"
  fi
}

init-datastore() {
  mkdir -p /hab/svc/builder-datastore
  cp -f /src/support/builder/datastore.toml /hab/svc/builder-datastore/user.toml
}

configure() {
  /src/support/builder/config.sh
}

install-packages() {
  hab pkg install \
  core/cacerts \
  core/net-tools \
  core/procps-ng \
  core/shadow \
  core/curl \
  -b -c stable
}

build-builder-component() {
  local component="$1"
  local status=0

  stop-"$component"

  if NO_INSTALL_DEPS=$(no_install_deps "builder-$component") \
  build "/src/components/builder-$component/habitat-dev"; then
    echo "builder-$component build succeeded"
  else
    status=$?
    echo "builder-$component build failed with $status"
  fi

  start-"$component"
  return $status
}

alias bb=build-builder
build-builder() {
  if [[ $(hab sup status) == "No services loaded." ]]; then
    start-builder
  fi

  if [[ "$#" -eq 0 ]]; then
    build-builder admin api jobsrv originsrv router sessionsrv worker
    return $?
  fi

  for component in "$@"; do
    if build-builder-component "$component"; then
      :
    else
      return $?
    fi
  done
}

ui-dev-mode() {
  for svc in sessionsrv worker api originsrv; do
  cat <<CONFIG | hab config apply builder-${svc}.default $(date +%s)
[github]
client_id = "Iv1.732260b62f84db15"
client_secret = "fc7654ed8c65ccfe014cd339a55e3538f935027a"
app_id = 5629
CONFIG
done
}

upload_github_keys() {
  if [[ -f "/src/.secrets/builder-github-app.pem" ]]; then
    for svc in sessionsrv worker api originsrv; do
      hab file upload "builder-${svc}.default" $(date +%s) "/src/.secrets/builder-github-app.pem"
    done
  else
    echo "Please follow instruction #6 here: https://github.com/habitat-sh/habitat/blob/master/BUILDER_DEV.md#pre-reqs"
    sleep 10
  fi
}

start-builder() {
  init-datastore
  start-datastore
  configure
  start-cache
  start-router
  start-admin
  start-admin-proxy
  start-api
  start-api-proxy
  start-jobsrv
  start-originsrv
  start-sessionsrv
  start-worker
  sleep 2
  generate_bldr_keys
  upload_github_keys
  echo "Builder Started: Navigate to http://localhost/#/pkgs/core to access the web UI."
}

start-admin() {
  hab svc load core/builder-admin --bind router:builder-router.default -s at-once
}

start-admin-proxy() {
  hab svc load core/builder-admin-proxy --bind http:builder-admin.default
}

start-api() {
  hab svc load core/builder-api --bind router:builder-router.default -s at-once
}

start-api-proxy() {
  hab svc load core/builder-api-proxy --bind http:builder-api.default
}

start-datastore() {
  hab svc load core/builder-datastore
}

start-jobsrv() {
  hab svc load core/builder-jobsrv --bind router:builder-router.default --bind datastore:builder-datastore.default -s at-once
}

start-originsrv() {
  hab svc load core/builder-originsrv --bind router:builder-router.default --bind datastore:builder-datastore.default -s at-once
}

start-router() {
  hab svc load core/builder-router -s at-once
}

start-sessionsrv() {
  hab svc load core/builder-sessionsrv --bind router:builder-router.default --bind datastore:builder-datastore.default -s at-once
}

start-worker() {
  hab svc load core/builder-worker --bind jobsrv:builder-jobsrv.default --bind depot:builder-api-proxy.default -s at-once
}

start-cache() {
  hab svc load core/sccache
}

stop-builder() {
  stop-cache
  stop-admin
  stop-admin-proxy
  stop-api
  stop-api-proxy
  stop-datastore
  stop-jobsrv
  stop-originsrv
  stop-router
  stop-sessionsrv
  stop-worker
}

stop-cache() {
  hab svc unload core/sccache
}

stop-admin() {
  hab svc unload core/builder-admin
}

stop-admin-proxy() {
  hab svc unload core/builder-admin-proxy
}

stop-api() {
  hab svc unload core/builder-api
}

stop-api-proxy() {
  hab svc unload core/builder-api-proxy
}

stop-datastore() {
  hab svc unload core/builder-datastore
}

stop-jobsrv() {
  hab svc unload core/builder-jobsrv
}

stop-originsrv() {
  hab svc unload core/builder-originsrv
}

stop-router() {
  hab svc unload core/builder-router
}

stop-sessionsrv() {
  hab svc unload core/builder-sessionsrv
}

stop-worker() {
  hab svc unload core/builder-worker
}

generate_bldr_keys() {
  KEY_NAME=$(hab user key generate bldr | grep -Po "bldr-\d+")
  for svc in api jobsrv worker; do
    hab file upload "builder-${svc}.default" $(date +%s) "/hab/cache/keys/${KEY_NAME}.pub"
    hab file upload "builder-${svc}.default" $(date +%s) "/hab/cache/keys/${KEY_NAME}.box.key"
  done
}

load_package() {
  hab pkg upload --url http://localhost:9636/v1 --auth "${HAB_AUTH_TOKEN}" "$@" --channel stable
}

load_packages() {
  if [[ -d /src/pkgs ]]; then
    for pkg in /src/pkgs/core*.hart ; do
      load_package "${pkg}"
    done
  fi
}

load_bootstrap_packages() {
  load_package /src/pkgs/core-hab-backline-0.39.0-dev-20171101044221-x86_64-linux.hart
  load_package /src/pkgs/core-hab-launcher-6083-20171101045646-x86_64-linux.hart
  load_package pkgs/core-hab-sup-0.34.0-dev-20170929202328-x86_64-linux.hart
  load_package pkgs/core-docker-17.09.0-20171001205930-x86_64-linux.hart
  load_package pkgs/core-elasticsearch-5.6.1-20171015201557-x86_64-linux.hart
}

origin() {
  local origin=${1:-core}
  if curl --fail localhost:9636/v1/depot/origins \
    -d "{\"name\":\"${origin}\"}" \
    -H "Authorization:Bearer:${HAB_AUTH_TOKEN}";
  then
    hab origin key generate "${origin}"
    hab origin key upload --url http://localhost:9636 -z ${HAB_AUTH_TOKEN} -s "${origin}"
  else
    echo "Failed to create origin ${origin}"
  fi
}

function psql() {
  PGPASSWORD=$(cat /hab/svc/builder-datastore/config/pwfile) hab pkg exec core/postgresql psql -U hab -h 127.0.0.1 "$@"
}

export -f psql

project() {
  curl http://localhost:9636/v1/projects -q \
    -d '{ "origin": "core", "plan_path": "nginx/plan.sh", "github": { "organization": "habitat-sh", "repo": "core-plans" } }' \
    -H "Authorization:Bearer:${HAB_AUTH_TOKEN}"
}

job() {
  curl POST http://localhost:9636/v1/jobs \
    -d '{"project_id":"core/nginx"}' \
    -H "Authorization:Bearer:${HAB_AUTH_TOKEN}"
}

# Cleanup any development touch files we laid down when checking to see if we could run NO_INSTALL_DEPS
local_cleanup() {
  for svc in admin admin-proxy api api-proxy datastore jobsrv originsrv router sessionsrv worker; do
    if [ -f "/src/components/builder-${svc}/cleanup" ]; then
      rm "/src/components/builder-${svc}/cleanup"
    fi
  done
}

dev_docs() {
  cat <<DOCS
Welcome to the development environment for Habitat & Builder.
The following commands are available:

1. Building Habitat Web
  * Ensure you have a unzipped download of packages from http://nunciato-shared-files.s3.amazonaws.com/pkgs.zip in the habitat directory
  * In the studio (after builder has started)
  * * origin <name> - create an origin and keys specified by the first argument. Default: core
  * * load_packages - load all the packages from core
  * Outside of the studio
  * * cd components/builder-web
  * * npm i - install the node packages
  * * npm load - run the web dev env
2. Building Builder
  * build-builder (alias: bb) - build all Builder components
  * build-builder admin - build the Admin Gateway
  * build-builder api - build the API Gateway
  * build-builder jobsrv - build the JobSrv
  * build-builder originsrv - build the OriginSrv
  * build-builder router - build the RouteSrv
  * build-builder sessionsrv - build the SessionSrv
  * build-builder worker - build the Worker
3. Running Builder
  * install-packages - Install all dependent packages
  * start-builder - run all Builder services
  * stop-builder - unload all Builder services
  * start-{svc} - load a specfic Builder service. See the
    above list of build targets for available services
  * stop-{svc} - unload a specific Builder service
  * ui-dev-mode - helper to switch the github app to localhost:3000
4. Helpers
  * psql - wrapper around psql to enable passwordless auth
  * upload_github_keys - internal function to upload github secret keys to the ring
5. Docs
  * dev_docs
DOCS
}

install-packages

ENV_CONFIG="/src/.secrets/habitat-env"

if [[ -f "${ENV_CONFIG}" ]]; then
  source "${ENV_CONFIG}"
else
  echo -e "${RED}.secrets/habitat-env is required. Please see DEVELOPING.md for getting started instructions.${NO_COLOR}"
  exit 1
fi

touch /etc/subuid
touch /etc/subgid
hab pkg exec core/shadow groupadd --force krangschnak
hab pkg exec core/shadow useradd --groups=tty --create-home -g krangschnak krangschnak || echo "User 'krangschnak' already exists"

trap local_cleanup EXIT

# Print out the docs
dev_docs
