#!/bin/bash

# Handle some arguments before running the application
# Supported arguments:
# -d|--debug: debug with -Wd arguments
PYDEBUG=false
PY='/usr/lib/solydxk/system/main.py'

APP='solydxk-system'

# Prepare for translations
# https://www.gnu.org/software/gettext/manual/html_node/Preparing-Shell-Scripts.html
. gettext.sh

TEXTDOMAIN=$APP
export TEXTDOMAIN
TEXTDOMAINDIR=/usr/share/locale
export TEXTDOMAINDIR

LIVE_WARNING=$(eval_gettext 'SolydXK System cannot run in a live environment.')

while getopts 'adt:' OPT; do
    case $OPT in
        a)
            # Exit when auto-start on live system
            [ -e /usr/lib/live/ ] && exit 0
            ;;
        d)
            PYDEBUG=true
            ARGS="$ARGS -d"
            ;;
        t)
            if [ -z "$OPTARG" ]; then
                echo "Usage: $0 [-d] [-t <theme>]"
                exit 1
            fi
            ARGS="$ARGS -t $OPTARG"
            ;;
        *)
            echo "Usage: $0 [-d] [-t <theme>]"
            exit 1
            ;;
    esac
done
shift $((OPTIND - 1))

if [ -e /usr/lib/live/ ]; then
    # Do not run in a live environment
    notify-send "$LIVE_WARNING"
    exit 0
fi

# Check if GUI is already started
if ! pgrep -f python3.*solydxk/system &>/dev/null; then
    if $PYDEBUG; then
        mkdir -p $HOME/.config/solydxk
        env PYTHONVERBOSE=1 python3 -Wd $PY $ARGS 2>&1 | tee $HOME/.config/solydxk/solydxk-system-pydebug.log
    else
        python3 $PY $ARGS
    fi
    # Remove the one time autostart desktop file
    rm -f $HOME/.config/autostart/solydxk-system-oneshot.desktop
fi
