#!/bin/bash

generate_config() {
  echo "* generating config"
  local device_type="$1"
  meshblu-util register --legacy -t "$device_type" --url http://meshblu.octoblu.dev:80 > meshblu.json
}

get_uuid() {
  cat meshblu.json | jq '.uuid' --raw-output
}

get_name() {
  cat package.json | jq '.name' --raw-output
}

update_device_schemas() {
  echo "* update device schemas"
  npm run generate:schema
  meshblu-util update -f schemas.json
}

add_name_to_device() {
  local name="$(get_name)"
  add_value_to_key "name" "Test $name"
}

add_owner_to_key() {
  local key="$1"
  local owner="$2"
  meshblu-util update -d "{\"$key\": [\"$owner\"]}"
}

add_value_to_key() {
  local key="$1"
  local owner="$2"
  meshblu-util update -d "{\"$key\": \"$owner\"}"
}

open_in_browser() {
  local uuid="$(get_uuid)"
  echo "* opening $uuid in browser"
  open "http://app.octoblu.dev/device/$uuid"
}

claim_device() {
  echo "* claim device"
  local owner="$1"
  add_owner_to_key "discoverWhitelist" "$owner" || exit 1
  add_owner_to_key "configureWhitelist" "$owner" || exit 1
  add_owner_to_key "sendWhitelist" "$owner" || exit 1
  add_owner_to_key "receiveWhitelist" "$owner" || exit 1
  add_owner_to_key "owner" "$owner" || exit 1
}

main() {
  if [ ! -f "./package.json" ]; then
    echo "Are you running this inside a connector?"
    exit 1
  fi

  local owner="$1"
  local device_type="$2"

  if [ -z "$owner" ]; then
    echo "Missing owner as the 1 argument"
    exit 1
  fi
  if [ -z "$device_type" ]; then
    echo "Missing device type as the 2 argument"
    exit 1
  fi
  echo "* generating"
  generate_config "$device_type" || exit 1
  add_name_to_device || exit 1
  update_device_schemas || exit 1
  claim_device "$owner" || exit 1
  open_in_browser || exit 1
  echo "* done"
}

main "$@"
