#!/bin/bash

# This script is designed to update and publish a chrome extension
# that already exists in the Chrome Web Store. It also depends on
# OAuth 2.0 credentials and a refresh token.

# Required arguments
# ==================
# There are 2 actions you can perform:
# 1. Update - upload a chrome extension to the Chrome Web Store
# 2. Publish - publish a chrome extension to the Chrome Web Store
# 
# The expected argument is one of the following: [ "update" | "publish" ]
#
# usage:
#   $ ./deploy.sh update
#   $ ./deploy.sh publish
#
ACTION=$1


# Configuration variables
# =======================

# The path to the OAuth 2.0 credentials.
# See: https://developer.chrome.com/webstore/using_webstore_api#beforeyoubegin
CREDENTIALS="./credentials.json"
CLIENT_ID=`jq -r ".installed.client_id" $CREDENTIALS`
CLIENT_SECRET=`jq -r ".installed.client_secret" $CREDENTIALS`

# The path to the refresh token
# See: https://gist.github.com/lewisrodgers/cdaa375f16941f3e1e03cc95338df506
TOKENS="./tokens.json"
REFRESH_TOKEN=`jq -r ".refresh_token" $TOKENS`

# This identifies which chrome extension will be updated or published.
APP_ID="fpea..."

# Chrome extensions need to be packaged as a zip file
# for uploading to the Chrome Web Store. The name of the zip
# doesn't matter. It's packaged then discarded during the
# update action.
FILE_NAME=packaged.zip


# Implementation
# ==============

function package() {
  echo "Packaging chrome extension..."
  zip -r $FILE_NAME ./app
}

function clean_up() {
  rm $FILE_NAME
}

function get_access_token() {
  ACCESS_TOKEN=`curl "https://accounts.google.com/o/oauth2/token" -d \
  "client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&refresh_token=${REFRESH_TOKEN}&grant_type=refresh_token&redirect_uri=urn:ietf:wg:oauth:2.0:oob" | jq -r ".access_token"`
}

function upload() {
  curl \
  -H "Authorization:Bearer ${ACCESS_TOKEN}" \
  -H "x-goog-api-version:2" \
  -X PUT \
  -T ${FILE_NAME} \
  -v "https://www.googleapis.com/upload/chromewebstore/v1.1/items/${APP_ID}"
}

function publish() {
  curl \
  -H "Authorization:Bearer ${ACCESS_TOKEN}" \
  -H "x-goog-api-version:2" \
  -H "Content-Length: 0" \
  -X POST \
  -v "https://www.googleapis.com/chromewebstore/v1.1/items/${APP_ID}/publish"
}

if [ "$ACTION" == "update" ]; then
  package
  get_access_token
  upload
  clean_up
elif [ "$ACTION" == "publish" ]; then
  get_access_token
  publish
fi