#!/bin/bash
# Helper to start Home Assistant Core inside the devcontainer

# Stop on errors
set -e

WD="${WORKSPACE_DIRECTORY:=/workspaces/frontend}"

if [ -z "${DEVCONTAINER}" ]; then
  echo "This task should only run inside a devcontainer, for local install HA Core in a venv."
  exit 1
fi

# Default to installing (or upgrading to) dev branch
coreURL="https://github.com/home-assistant/core.git"
ref="dev"

while getopts "hr:s" opt; do
  case $opt in
    h) # Help
      echo "Usage: $0 [-h|-r <ref>|-s]"
      echo -n "Install and run core at the given ref, i.e. branch, tag, or commit. The dev branch is used if no option is specified."
      echo "The -s flag skips the install/upgrade, using whatever version is currently installed."
      exit 0
      ;;
    r) # Git ref
      ref="${OPTARG}"
      ;;
    s) # Skip (use current install)
      ref=""
      ;;
    *)
      echo "Try $0 -h for help" >&2
      exit 1
      ;;
  esac
done

if [ -n "$ref" ]; then
  echo "Installing Home Assistant core at ${ref}..."
  python3 -m pip install --user --upgrade --src "$HOME/src" \
  --editable "git+${coreURL}@${ref}#egg=homeassistant"
  (cd ~/src/homeassistant && exec python3 -m script.translations develop --all)
fi

if [ ! -d "${WD}/config" ]; then
  echo "Creating default configuration."
  mkdir -p "${WD}/config";
  hass --script ensure_config -c config
  echo "demo:

logger:
  default: info
  logs:
    homeassistant.components.frontend: debug
" >> "${WD}/config/configuration.yaml"

  if [ -n "${HASSIO}" ]; then
  echo "
# frontend:
#   development_repo: ${WD}

hassio:
  development_repo: ${WD}" >> "${WD}/config/configuration.yaml"
  else
  echo "
frontend:
  development_repo: ${WD}

# hassio:
#   development_repo: ${WD}" >> "${WD}/config/configuration.yaml"
  fi

  if [ -n "${CODESPACES}" ]; then
  echo "
http:
  use_x_forwarded_for: true
  trusted_proxies:
    - 127.0.0.1
" >> "${WD}/config/configuration.yaml"
  fi
fi

hass -c "${WD}/config"