#!/bin/bash
set -e

URL_VERSION="https://raw.githubusercontent.com/home-assistant/hassio/master/version.json"
URL_GENERIC_HC="https://raw.githubusercontent.com/home-assistant/hassio-build/master/generic-hc"

# Test env
if [ ! -f $(command -v hassio-hc) ]; then
    echo "[ERROR] hassio-hc is not installed!"
    exit 1
fi

# Check system options
if [ -x $(command -v systemctl) ]; then
    INIT_SYSTEM=systemd
else
    INIT_SYSTEM=sysvinit
fi

VERSION=$(curl -s $URL_VERSION | jq -e -r '.generic')
CMD_BIN=$(command -v hassio-hc)

curl -sL "$URL_GENERIC_HC/$VERSION" > "$CMD_BIN"
if [ $? -eq 0 ]; then
    chmod a+x "$CMD_BIN"
    echo "OK"

    # restart service
    if [ "$INIT_SYSTEM" == "systemd" ]; then
        nohup systemctl restart hassio-hc.service > /dev/null 2>&1
    fi
else
    echo "[ERROR] Can't load hass-hc."
    exit 1
fi
