#!/usr/bin/with-contenv bashio
# ==============================================================================
# Start config checker service
# ==============================================================================
VERSION=$(bashio::config 'version')

CMD_OPTIONS=("--disable-pip-version-check" "--find-links" "${WHEELS_LINKS}")

# Generate install string
if [[ "${VERSION}" =~ latest|stable ]]; then
    CMD_OPTIONS+=("homeassistant")
elif [ "${VERSION}" == "beta" ]; then
    CMD_OPTIONS+=("--pre")
    CMD_OPTIONS+=("homeassistant")
elif [ "${VERSION}" == "dev" ]; then
    CMD_OPTIONS+=("git+git://github.com/home-assistant/core.git@dev")
else
    CMD_OPTIONS+=("homeassistant==${VERSION}")
fi

bashio::log.info "Don't worry, this temporary installation is not overwriting your current one."
bashio::log.info "Installing Home Assistant: ${VERSION}..."
bashio::log.info "Please be patient, this might take a few minutes..."

# Install Home Assistant with the requested version
if ! PIP_OUTPUT=$(pip3 install "${CMD_OPTIONS[@]}" 2>&1); then
    bashio::log.error "An error occurred while installing Home Assistant:"
    bashio::log "${PIP_OUTPUT}"
    bashio::exit.nok
fi
INSTALLED_VERSION="$(pip freeze | grep homeassistant)"
bashio::log.info "Installed Home Assistant ${INSTALLED_VERSION##*=}"

# Making a temporary copy of your configuration
bashio::log.info "Making a copy of your configuration for checking..."
rsync -avr --exclude='*home-assistant_v2*' /config/ /tmp/config --quiet

# Start configuration check
bashio::log.info "Checking your configuration against this version..."

if ! hass -c /tmp/config --script check_config > /share/check_config.txt; then
    # The configuration check exited with an error
    bashio::log.error "The configuration check did not pass!"
    bashio::log.error "See the output below for more details."

    grep -v homeassistant.util.package /share/check_config.txt | head -n 15

    bashio::log.info "The full output has been written to /share/check_config.txt"
    bashio::exit.nok
fi

# Scan configuration check output for occurrences of "ERROR"
if grep -i ERROR /share/check_config.txt > /dev/null; then
    # An "ERROR" occurrence has been found, exit with an error
    bashio::log.error "Found an error in the log output of the check!"
    bashio::log.error "See the output below for more details."

    grep -i ERROR /share/check_config.txt

    bashio::log.info "The full output has been written to /share/check_config.txt"
    bashio::exit.nok
fi

# You rock! <(*_*)>
bashio::log.info "Configuration check finished - no error found! :)"
