#!/bin/bash
# curl -o- -L https://gist.githubusercontent.com/bdraco/43f8043cb04b9838383fd71353e99b18/raw/core_integration_pr | bash /dev/stdin -d domain -p 12345

while getopts d:p: flag
do
    case "${flag}" in
        d) domain="${OPTARG}";;
        p) pull_request="${OPTARG}";;
    esac
done


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

current_dir="${PWD}"
tmp_git_dir=/tmp/core_git

set -e
clean_up () {
    ARG=$?
    info "Cleaning up"
    cd "$current_dir"
    rm -rf "${tmp_git_dir}"
    exit $ARG
}
trap clean_up EXIT


if [ -z "$(command -v "git")" ]; then
    error "'git' is not installed"
fi

if [ -z "$(command -v "jq")" ]; then
    error "'jq' is not installed"
fi


info "Current dir is ${current_dir}"

if [[ -z "${domain}" ]]; then
    error "Missing domain (-d) argument";
fi

if [[ -z "${pull_request}" ]]; then
    error "Missing pull request (-p) argument";
fi

if [[ ! -f ".HA_VERSION" ]]; then
    error "Not a Home Assistant folder!"
fi


info "Cloning core to "
git clone --depth 1 https://github.com/home-assistant/core.git "${tmp_git_dir}"
cd "${tmp_git_dir}"

info "Checking out PR#${pull_request}"
git fetch origin --depth 1 "pull/${pull_request}/head"
git checkout `git ls-remote origin pull/${pull_request}/head | awk '{print $1}'`

if [[ ! -d "${tmp_git_dir}/homeassistant/components/${domain}" ]]; then
    error "Integration with ${domain} does not exist in PR#${pull_request}"
fi

info "Removing current folder ${current_dir}/custom_components/${domain}"
rm -rf "${current_dir}/custom_components/${domain}"

info "Copying integration files"
mkdir -p "${current_dir}/custom_components"
mv "${tmp_git_dir}/homeassistant/components/${domain}" "${current_dir}/custom_components/"

if [[ -f "${current_dir}/custom_components/${domain}/strings.json" ]]; then
    mkdir -p "${current_dir}/custom_components/${domain}/translations"
    mv "${current_dir}/custom_components/${domain}/strings.json" "${current_dir}/custom_components/${domain}/translations/en.json"
fi

jq --arg pull_request "${pull_request}" '.version = $pull_request' "${current_dir}/custom_components/${domain}/manifest.json" > tmp && mv -f tmp "${current_dir}/custom_components/${domain}/manifest.json"

info "DONE!"
info "You now need to restart Home Assistant"
info "NOTE: If the PR changed anything outside of it´s own folder this method will not work."
info "If you want to remove this, you need to delete the ${current_dir}/custom_components/${domain} folder"