#!/bin/sh
# Install or update the SBC Spotify upload helper, a browser extension for Chrome or Edge, on a Mac
# or Linux.
# Run in Terminal:
#
#   curl -fsSL https://www.spekebaptistchurch.org.uk/tools/spotify-upload-helper/install.sh | sh
#
# It downloads the helper from the church website, checks the download against the checksum the
# website publishes, and puts it in a folder of its own. Chrome and Edge only let you add an
# extension that isn't from their store by hand, so the first time you finish with "Load
# unpacked"; after that, running this again updates the folder in place.
set -eu

version='0.4.4'
zip_url='https://www.spekebaptistchurch.org.uk/tools/spotify-upload-helper/spotify-upload-helper.zip'
sha256='e2d68a8801615fa3db6cfc517c2c26d6fb836335e5dfe70f593451de6e0f4c13'

if [ "$(uname)" = Darwin ]; then
  folder="$HOME/Library/Application Support/SBC/spotify-upload-helper"
else
  folder="${XDG_DATA_HOME:-$HOME/.local/share}/sbc/spotify-upload-helper"
fi

fail() { printf '%s\n' "$1" >&2; exit 1; }
[ -n "$sha256" ] || fail 'The website has no download for the helper at the moment. Try again later.'
command -v unzip >/dev/null || fail 'This needs "unzip". Install it (for example: sudo apt install unzip) and run this again.'

zip=$(mktemp)
trap 'rm -f "$zip"' EXIT
echo "Downloading version $version from the church website..."
curl -fsSL "$zip_url" -o "$zip"
if command -v sha256sum >/dev/null; then hash=$(sha256sum "$zip"); else hash=$(shasum -a 256 "$zip"); fi
[ "${hash%% *}" = "$sha256" ] ||
  fail "The download doesn't match the checksum the website published, so it was not installed. Try again later."

first_time=yes
[ -f "$folder/manifest.json" ] && first_time=
rm -rf "$folder"
mkdir -p "$folder"
unzip -q "$zip" -d "$folder"

copied=
if command -v pbcopy >/dev/null; then printf '%s' "$folder" | pbcopy && copied=' (the folder path is copied)'
elif command -v wl-copy >/dev/null; then printf '%s' "$folder" | wl-copy && copied=' (the folder path is copied)'
elif command -v xclip >/dev/null; then printf '%s' "$folder" | xclip -selection clipboard && copied=' (the folder path is copied)'
fi

echo
echo "Installed version $version in $folder$copied."
echo
if [ "$first_time" ]; then
  if [ "$(uname)" = Darwin ]; then paste='press Cmd+Shift+G, then Cmd+V'; else paste='press Ctrl+L, then Ctrl+V'; fi
  echo 'To finish, in Chrome or Edge:'
  echo '  1. Go to chrome://extensions (in Edge: edge://extensions).'
  echo '  2. Turn on "Developer mode".'
  echo "  3. Click \"Load unpacked\" and choose $folder"
  echo "     (to paste the path, $paste)."
  echo '  4. Click the Extensions button (the puzzle piece) and pin "SBC Spotify upload helper".'
else
  echo 'To finish, go to chrome://extensions (or edge://extensions) and click the reload arrow on'
  echo '"SBC Spotify upload helper", or restart the browser.'
fi
