#!/usr/bin/env bash

# Generated by Hydraulic Conveyor: https://www.hydraulic.dev
#
# This script will download the app, unpack it to /Applications or ~/Applications and start it up.

set -e

mac_amd64_zip_url="https://www.gaardeon.org/coppercook/coppercook-0.9.8-mac-amd64.zip"
mac_aarch64_zip_url="https://www.gaardeon.org/coppercook/coppercook-0.9.8-mac-aarch64.zip"
app_name="CopperCook"

arch=$( arch )
if [[ $arch == "i386" ]]; then
  mac_zip_url="$mac_amd64_zip_url"
elif [[ $arch == "arm64" ]]; then
  mac_zip_url="$mac_aarch64_zip_url";
else
  echo "Unsupported CPU architecture: $arch"
  exit 1
fi

tmpdir=$( mktemp -d -t download )
tmpfile="$tmpdir/app.zip"
function cleanup() {
  cd "$TMPDIR"
  [ -e "$tmpfile" ] && rm -f "$tmpfile"
  rmdir "$tmpdir"
}
trap cleanup ERR

echo "Downloading $app_name ..."
curl -L --output "$tmpfile" --progress-bar "$mac_zip_url"

if [ -w /Applications ]; then
  cd /Applications
else
  if [ ! -d "$HOME/Applications" ]; then
    mkdir "$HOME/Applications"
  fi
  cd "$HOME/Applications"
fi

if [ -d "${app_name}.app" ]; then
  echo "App folder ${app_name}.app already exists, removing."
  rm -r "${app_name}.app"
fi

echo "Extracting to $PWD ..."
ditto -x -k $tmpfile .

# Quarantine bits aren't set by curl in current versions of macOS, but who knows if/when this may change.
xattr -r -d com.apple.quarantine "${app_name}.app"

open "${app_name}.app"

cleanup
exit 0

