#!/usr/bin/env bash

set -e

if [[ "$#" -ne 4 && "$#" -ne 5 ]]; then
    echo 'Upload an OpenRCT2 build to openrct2.org.'
    echo ''
    echo 'Usage: upload-build <path> <flavour> <version> <sha1> [<branch>]'
    echo 'Flavours: windows-portable-x86, windows-portable-x64'
    echo '          windows-installer-x86, windows-installer-x64'
    echo '          windows-symbols-x86, windows-symbols-x64'
    echo '          macos'
    echo '          linux-i686, linux-x86_64'
    echo '          android-arm, android-x86'
    echo ''
    echo 'Environment variable ''OPENRCT2_ORG_TOKEN'' must be set.'
    exit 1
fi

path=$1
flavour=$2
version=$3
sha1=$4
branch=$5

if [ -n "$branch" ]; then
    versionextra=-$branch-${sha1::7}
fi
filename=OpenRCT2-$version$versionextra-$flavour

echo -e "\033[0;36mUploading to openrct2.org as '$filename'..."
if [ -z "$OPENRCT2_ORG_TOKEN" ]; then
    echo -e "\033[0;31mOPENRCT2_ORG_TOKEN not set"
    exit 1
fi
# Use HTTP1.1 as a workaround for curl bug:
# https://github.com/actions/runner-images/issues/7329
# https://github.com/curl/curl/issues/10591
curl --include -m 300 --connect-timeout 5 -o - \
    --http1.1 \
    --form "key=$OPENRCT2_ORG_TOKEN" \
    --form "fileName=$filename" \
    --form "version=$version" \
    --form "gitHash=$sha1" \
    --form "gitBranch=$branch" \
    --form "file=@$path" \
    "https://openrct2.org/altapi/?command=push-build"
