#!/bin/sh

clean() {
    if [ -r "$tempConf" ]; then
        mv -f "$tempConf" "$confDir/snes9x.xml"
    fi
}

if [ -z "$XDG_CONFIG_HOME" ]; then
    homeDir="$HOME/.config/lostvikings"
else
    homeDir="$XDG_CONFIG_HOME/lostvikings"
fi

locale=$(locale | sed -ne 's/^[^=]*="*\([^.]*\)\..*$/\1/g;1p')
localeShort=$(echo "$locale" | sed -e 's/_.*$//')

sysDir="/usr/share/lostvikings"
confDir="$HOME/.snes9x"
tempConf="$(mktemp)"
mkdir -p "$homeDir" "$confDir" 2> /dev/null

cd "$confDir"
if [ -r "./snes9x.xml" ]; then
    mv -f "./snes9x.xml" "$tempConf"
    trap clean EXIT
fi

cp -n "/etc/lostvikings/lostvikings.conf" "$homeDir/snes9x.conf"
ln -s "$homeDir/snes9x.conf" "./snes9x.xml"

if [ -r "$sysDir/lostv-$locale.smc" ]; then
    exec="$sysDir/lostv-$locale.smc"
elif [ -r "$sysDir/lostv-$localeShort.smc" ]; then
    exec="$sysDir/lostv-$localeShort.smc"
else
    exec="$sysDir/lostv.smc"
fi
cd "$homeDir"
exec snes9x-gtk "$exec"
