#!/usr/bin/env bash

VERSION="$1"
PLATFORM="$2"

SAFE_VERSION=$(echo "$VERSION" | sed -nE 's/-/./p')

TMP_ROOT="/tmp/godot"
mkdir -p "$TMP_ROOT"

BINARY_NAME="Godot_v${VERSION}_${PLATFORM}"
TMP_PATH="$TMP_ROOT/godot_${VERSION}_${PLATFORM}.zip"
LOCAL_PATH="$HOME/.local/share/godot/export_templates/$SAFE_VERSION"

ARTIFACT_PATH="https://github.com/godotengine/godot-builds/releases/download/${VERSION}/${BINARY_NAME}.zip"
TEMPLATES_PATH="https://github.com/godotengine/godot/releases/download/${VERSION}/Godot_v${VERSION}_export_templates.tpz"

wget -O "$TMP_PATH" "$ARTIFACT_PATH"
unzip -o "$TMP_PATH" -d "$(pwd)"
mv "$BINARY_NAME" /usr/bin/godot

mkdir -p "$LOCAL_PATH"
wget -O "${TMP_ROOT}/templates.tpz" "$TEMPLATES_PATH"
unzip -o "${TMP_ROOT}/templates.tpz" -d "${TMP_ROOT}/godot_templates"
mv "${TMP_ROOT}/godot_templates/templates/*" "$LOCAL_PATH/"

rm -r "$TMP_ROOT"