set -x
# Install file, curl, jq and LLVM v15 in whatever distribution you are using, e.g. `apt install file curl llvm-15 jq`
# API documentation: https://api.azul.com/metadata/v1/docs/swagger
JAVA_VERSION=21;
JAVA_TYPE="jre"
BASE_URL="https://api.azul.com/metadata/v1/zulu/packages/?java_version=${JAVA_VERSION}&os=macos&archive_type=tar.gz&java_package_type=${JAVA_TYPE}&javafx_bundled=true&crac_supported=false&crs_supported=false&support_term=lts&latest=true&release_status=ga&availability_types=CA&certifications=tck&page=1&page_size=100&arch="
X86=$(curl ${BASE_URL}amd64)
AARCH64=$(curl ${BASE_URL}aarch64)
WORKDIR=workdir
AARCH64_NAME=$(echo "${AARCH64}" | jq -r '.[].name')
X86_NAME=$(echo "${X86}" | jq -r '.[].name')

function merge() {
  if [ "$(command -v lipo)" ]; then
    lipo -create -output "${1}" "${2}" "${3}"
  elif [ "$(command -v llvm-lipo-15)" ]; then
    llvm-lipo-15 -create -output "${1}" "${2}" "${3}"
  fi
}

function get_jres() {
  local localPwd=$(pwd)
  if [ ! -d "${WORKDIR}" ]; then mkdir "${WORKDIR}"; fi
	cd "${WORKDIR}" || exit 2
	curl --location "$(echo "${AARCH64}" | jq -r '.[].download_url')" --output "${AARCH64_NAME}"
	curl --location "$(echo "${X86}" | jq -r '.[].download_url')" --output "${X86_NAME}"
	echo "${AARCH64}" > ".version"
	cd "${localPwd}" || exit 2
}

function copy() {
  # Trim the root path
  FILE="${1#*/}"
  if [ ! -e "target/${FILE}" ]; then
    # Only make directories if we aren't looking at the root files
    if [[ "${FILE}" == *"/"* ]]; then mkdir -p "target/${FILE%/*}"; fi
    if file "${1}" | grep -q 'Mach-O' ; then
      merge "target/${FILE}" "x64/${FILE}" "aarch64/${FILE}"
      if file "${1}" | grep -q 'executable'; then
        chmod 755 "target/${FILE}"
      fi
    else
      cp -a "${1}" "target/${FILE}"
    fi
  fi
}

function directory_iterate() {
  while IFS= read -r -d '' file
  do
    copy "${file}" &
  done <   <(find "${1}" -type f,l -print0)
  wait
}

function create_universal_target() {
  local localPwd="$(pwd)"
  cd "${WORKDIR}" || exit 2
  mkdir aarch64 && tar --strip-components 1 --directory=aarch64 -xf "${AARCH64_NAME}"
  mkdir x64 && tar --strip-components 1 --directory=x64 -xf "${X86_NAME}"
  #if [ -d target ]; then rm -r target; fi
  mkdir target
  # Do both just in case there are non-shared files
  directory_iterate aarch64
  directory_iterate x64
  # Remove extracted files to save disk space
  #rm -rf x64
  #rm -rf aarch64
  cd "${localPwd}" || exit 2
}

function package() {
  local localPwd="$(pwd)"
  # Remove generic JDK information
  cd "${1}/"*"${JAVA_TYPE}"*"/Contents" || exit 2
  rm -r "Info.plist"
  rm -r "MacOS"
  rm -r "_CodeSignature"
  # The jre directory is what we point to as "JAVA_HOME" in the script; this is the bundled jdk.
  mv "Home" "jre"
  cd ${localPwd} || exit 2
  jar --create --file jre.os-x-"$(jq -r '.[].java_version | join(".")' < "${WORKDIR}/.version").jar" -C "${WORKDIR}/target/"*"${JAVA_TYPE}"*"/Contents" .
}

function generate_josm() {
  mkdir -p "${WORKDIR}/JOSM.app/Contents/MacOS"
  mkdir -p "${WORKDIR}/JOSM.app/Contents/jars"
  cp -R "${WORKDIR}/target/"*"${JAVA_TYPE}"*"/Contents" "${WORKDIR}/JOSM.app/"
  cat << EOF > "${WORKDIR}/JOSM.app/Contents/MacOS/JOSM"
#!/bin/bash
cd "\$(dirname \$0)/.."
JAVA_OPTS="--add-modules java.scripting,java.sql,javafx.controls,javafx.media,javafx.swing,javafx.web \
               --add-exports=java.base/sun.security.action=ALL-UNNAMED \
               --add-exports=java.desktop/com.sun.imageio.plugins.jpeg=ALL-UNNAMED \
               --add-exports=java.desktop/com.sun.imageio.spi=ALL-UNNAMED"
# shellcheck disable=SC2086
function start_josm() {
  if arch -arm64 /bin/bash -c 'echo arm64'; then
    arch -arm64 -e JAVA_HOME="./jre/" ./jre/bin/java \${JAVA_OPTS} -jar jars/josm-tested.jar "\${@}"
  else
    JAVA_HOME="./jre/" ./jre/bin/java \${JAVA_OPTS} -jar jars/josm-tested.jar "\${@}"
  fi
}
while true; do
  start_josm
  if [ "z\$?" != "z9" ]; then
    break;
  fi
  echo ">> restarting josm..."
done
EOF
  chmod +x "${WORKDIR}/JOSM.app/Contents/MacOS/JOSM"
  curl -L https://josm.openstreetmap.de/josm-tested.jar --output "${WORKDIR}/JOSM.app/Contents/jars/josm-tested.jar"
  # TODO generate Info.plist (this is the only bit that is specific to Mac)
  # Note: if we keep a static copy of it, note how it was generated here!
  cp /Applications/JOSM.app/Contents/Info.plist "${WORKDIR}/JOSM.app/Contents"
}

if [ "$(echo "${AARCH64}" | jq '.[].distro_version')" == "$(echo "${X86}" | jq '.[].distro_version')" ]; then
	if [ -d "${WORKDIR}" ] && [ -f "${WORKDIR}/.version" ]; then
		if [ "$(echo "${AARCH64}" | jq '.[].distro_version')" != "$(jq '.[].distro_version' < "${WORKDIR}/.version")" ]; then
			rm -rf "${WORKDIR}"
			get_jres
		fi
	else
		get_jres
	fi
  if [ ! -d "${WORKDIR}/target" ]; then create_universal_target; fi
  if [ ! -f "jre.os-x-$(jq -r '.[].java_version | join(".")' < "${WORKDIR}/.version").jar" ]; then package "${WORKDIR}/target"; fi
  # Everything up to this point is usable by other people
  generate_josm
else
	echo "Mismatched versions"
	echo "${X86}" | jq
	echo "${AARCH64}" | jq
	exit 1
fi
