#!/bin/bash
# wget -q -O - https://raw.githubusercontent.com/devmel/hass_airsend-addon/master/install | bash -
set -e

RED_COLOR='\033[0;31m'
GREEN_COLOR='\033[0;32m'
GREEN_YELLOW='\033[1;33m'
NO_COLOR='\033[0m'

declare haPath
declare -a paths=(
    "$PWD"
    "$PWD/config"
    "/config"
    "$HOME/.homeassistant/"
    "/usr/share/hassio/homeassistant/"
)

function info () { echo -e "${GREEN_COLOR}INFO: $1${NO_COLOR}";}
function warn () { echo -e "${GREEN_YELLOW}WARN: $1${NO_COLOR}";}
function error () { echo -e "${RED_COLOR}ERROR: $1${NO_COLOR}"; if [ "$2" != "false" ]; then exit 1;fi; }

function checkRequirement () {
    if [ -z "$(command -v "$1")" ]; then
        error "'$1' is not installed"
    fi
}

checkRequirement "wget"
checkRequirement "unzip"

info "Trying to find the correct directory..."
for path in "${paths[@]}"; do
    if [ -n "$haPath" ]; then
        break
    fi

    if [ -d "$path/addons" ]; then
        haPath="$path/addons"
    fi
done

if [ -n "$haPath" ]; then
    info "Found Home Assistant addons directory at '$haPath'"
    cd "$haPath" || error "Could not change path to $haPath"

    info "Downloading AirSend Home Assistant Addon"
	wget "https://github.com/devmel/hass_airsend-addon/releases/download/latest/hass_airsend-addon.zip"

    if [ -d "$haPath/airsend" ]; then
        warn "airsend directory already exist, cleaning up..."
        rm -R "$haPath/airsend"
    fi

    info "Creating airsend directory..."
    mkdir "$haPath/airsend"

    info "Unpacking hass_airsend..."
    unzip "$haPath/hass_airsend-addon.zip" -d "$haPath/airsend" >/dev/null 2>&1

    info "Removing hass_airsend zip file..."
    rm "$haPath/hass_airsend-addon.zip"
    info "Installation complete."
    echo
    info "Remember to install and start airsend addon in Supervisor -> Add-on store -> Local add-ons"

else
    echo
    error "Could not find the directory for Home Assistant addons" false
    echo "Manually change the directory to the root of your Home Assistant configuration"
    echo "With the user that is running Home Assistant"
    echo "and run the script again"
    exit 1
fi
