#!/bin/bash

TARGET_LABEL="needs design preview"

if [[ "$NETLIFY" != "true" ]]; then
  echo "This script can only be run on Netlify"
  exit 1
fi

function createStatus() {
  state="$1"
  description="$2"
  target_url="$3"
  curl -X POST -H "Accept: application/vnd.github.v3+json" -H "Authorization: token $GITHUB_TOKEN" \
    "https://api.github.com/repos/home-assistant/frontend/statuses/$COMMIT_REF" \
    -d '{"state": "'"${state}"'", "context": "Netlify/Design Preview Build", "description": "'"$description"'", "target_url":  "'"$target_url"'"}'
}


if [[ "${PULL_REQUEST}" == "true" ]]; then
  if [[ "$(curl -sSLf -H "Accept: application/vnd.github.v3+json" -H "Authorization: token $GITHUB_TOKEN" \
    "https://api.github.com/repos/home-assistant/frontend/pulls/${REVIEW_ID}" | jq '.labels[].name' -r)" =~ "$TARGET_LABEL" ]]; then
    createStatus "pending" "Building design preview" "https://app.netlify.com/sites/home-assistant-gallery/deploys/$BUILD_ID"
    gulp build-gallery
    if [ $? -eq 0 ]; then
      createStatus "success" "Build complete" "$DEPLOY_PRIME_URL"
    else
      createStatus "error" "Build failed" "https://app.netlify.com/sites/home-assistant-gallery/deploys/$BUILD_ID"
    fi
  else
    createStatus "success" "Build was not requested by PR label"
  fi
elif [[ "$INCOMING_HOOK_BODY" == "NIGHTLY" ]]; then
  gulp build-gallery
fi
