#!/bin/sh

GAME_DIR=~/.local/state/BAR
CONFIG_FILE=${GAME_DIR}/chobby_config.json
SETTINGS_FILE=${GAME_DIR}/springsettings.cfg
DATASIZE="8388608" # 8G

xm_log() {
	echo -n "$@\nDo you want to run Beyond All Reason anyway?\n\
(If you don't increase these limits, spring might fail to work properly.)" | \
		/usr/X11R6/bin/xmessage -file - -center -buttons yes:0,no:1 -default no
}

if [ $(ulimit -Sd) -lt ${DATASIZE} ]; then
	ulimit -Sd ${DATASIZE} || \
		xm_log "Cannot increase datasize-cur to at least ${DATASIZE}"
		[ $? -eq 0 ] || exit
fi

# setup
# XXX: empty server address to disallow multiplayer while desyncs
#      once solved, set address to "server4.beyondallreason.info"
[[ -d ${GAME_DIR} ]] || mkdir -p ${GAME_DIR}
[[ -f ${CONFIG_FILE} ]] || cat > ${CONFIG_FILE} <<EOF
{
  "server": {
    "address": "",
    "port": 8200,
    "protocol": "spring",
    "serverName": "BAR"
  },
  "game": "byar"
}
EOF
[[ -f ${SETTINGS_FILE} ]] || cat > ${SETTINGS_FILE} <<EOF
RapidTagResolutionOrder = repos-cdn.beyondallreason.dev;repos.beyondallreason.dev
EOF

# update
PRD_HTTP_SEARCH_URL=https://files-cdn.beyondallreason.dev/find
PRD_RAPID_USE_STREAMER=false
PRD_RAPID_REPO_MASTER=https://repos-cdn.beyondallreason.dev/repos.gz
export PRD_HTTP_SEARCH_URL PRD_RAPID_USE_STREAMER PRD_RAPID_REPO_MASTER
/usr/local/bin/pr-downloader \
	--filesystem-writepath ${GAME_DIR} \
	--download-game byar:test \
	--download-game byar-chobby:test

# start
/usr/local/bin/spring --write-dir ${GAME_DIR} \
	--isolation --isolation-dir /usr/local/share/games/spring/ \
	--menu rapid://byar-chobby:test "$@"
