#!/bin/sh

set -e

# Esnure User Is In docker Group
if ! id -nGz | grep -qzxF 'docker'; then
    pkexec /usr/sbin/usermod -aG docker "$(id -un)"
fi

# All Feature Flags
export AVAILABLE_FEATURES="$(tr '\n' ' ' < /usr/share/minecraft-pi/client/features)"

# Print Feature Flags Option
if [ "$1" = "--print-features" ]; then
    echo "${AVAILABLE_FEATURES}"
    exit 0
fi

# Export Important Variables
export ZENITY_CLASS='Minecraft - Pi edition'
export DOCKER_COMPOSE_YML="/usr/share/minecraft-pi/client/docker-compose.yml"

# Ensure Features Are Selected
if [ -z "${MCPI_FEATURES+x}" ]; then
    MCPI_FEATURES="$(eval "zenity --class \"${ZENITY_CLASS}\" --list --checklist --width 400 --height 400 --column 'Enabled' --column 'Feature' ${AVAILABLE_FEATURES}")"
fi
if [ -z "${MCPI_RENDER_DISTANCE+x}" ]; then
    MCPI_RENDER_DISTANCE="$(zenity --class "${ZENITY_CLASS}" --list --radiolist --width 400 --height 400 --text 'Minecraft Render Distance:' --column 'Selected' --column 'Name' FALSE 'Far' FALSE 'Normal' TRUE 'Short' FALSE 'Tiny')"
fi
if [ -z "${MCPI_USERNAME+x}" ]; then
    MCPI_USERNAME="$(zenity --class "${ZENITY_CLASS}" --entry --text 'Minecraft Username:' --entry-text 'StevePi')"
fi
export MCPI_FEATURES
export MCPI_RENDER_DISTANCE
export MCPI_USERNAME

# Allow X11 Connections From Root
xhost local:root

# Prepare Environment
export USER_HOME="${HOME}"
export USER_UID="$(id -u)"
export USER_GID="$(id -g)"
get_gid() {
    echo "$(getent group "$1" | cut -d : -f 3)"
}
export USER_OTHER_GIDS="$(get_gid video) $(get_gid render)"

# Run
set +e
sg docker /usr/lib/minecraft-pi/pre-launch.sh
RET=$?
set -e

# Handle Crash
if [ ${RET} -ne 0 ]; then
    zenity --class "${ZENITY_CLASS}" --error --no-wrap --text 'Minecraft: Pi Edition has crashed!\n\nExit Code: '${RET}'\n\n<a href="file:///tmp/minecraft-pi">Open Log Folder</a>\n<a href="https://gitea.thebrokenrail.com/TheBrokenRail/minecraft-pi-reborn#troubleshooting">Open Troubleshooting Guide</a>'
    exit ${RET}
fi