#!/bin/bash

#  This file is part of Atarashii.
#
#  Atarashii is free software: you can redistribute it and/or
#  modify it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Atarashii is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#  GNU General Public License for more details.
# 
#  You should have received a copy of the GNU General Public License along with
#  Atarashii. If not, see <http://www.gnu.org/licenses/>.


# Atarashii Crash Wrapper ------------------------------------------------------
# ------------------------------------------------------------------------------

# Autostart wait
if [ "$1" == "auto" ]; then 
    sleep 2
fi

# Start Atarashii
RESTART=0
MAX=3
CODE=0
echo "Starting Atarashii..."
while [ $RESTART -lt $MAX ]
do
    # Start
    ./debug.py $1 $2
    
    # Vars
    let CODE=$?
    let RESTART=RESTART+1
    
    # Logout check
    if [ -e ~/.atarashii/logout ]; then
        rm ~/.atarashii/logout
        exit 0
    
    # Checks
    elif [ $CODE -eq 0 ]; then # dont care about xwindow stuff
        echo "Atarashii has exited normally."
        exit 0
    
    elif [ $CODE -eq 69 ]; then
        echo "Atarashii is already running."
        exit 0
    
    elif [ $CODE -eq 70 ]; then
        echo "70" >~/.atarashii/crashed
        echo "Atarashii crashed due to an internal error!"  
        if [ $RESTART -lt $MAX ]; then
            echo "Restarting..."
        fi
    
    elif [ $CODE -eq 75 ]; then
        echo "Atarashii could not be started!"
        exit 2
    
    elif [ $CODE -eq -9 ]; then
        echo "Atarashii has been killed."
        exit 1
    
    elif [ $CODE -eq -15 ]; then
        echo "Atarashii has been terminated."
        exit 1
    
    else
        echo $CODE >~/.atarashii/crashed
        echo "Atarashii crashed due to an external error!"
        if [ $RESTART -lt $MAX ]; then
            echo "Restarting..."
        fi
    fi
done

