#! /bin/bash
# vim: set tabstop=4 shiftwidth=4 expandtab filetype=sh:

if [[ ( $(grep USB <<< $myTTY) || $(grep AMA <<< $myTTY) || $SSH_CLIENT || $REMOTEHOST ) && ! $DISPLAY ]]; then
    echo "Please run LinApple on the console, or in an X Window."
else
    if [[ $(dpkg -l libsdl1.2debian libcurl3 zlib1g libzip2 2> /dev/null | grep ^ii | wc -l) -ne 4 ]]; then
        echo "Configuring LinApple libraries (this may take a moment)..."
        sudo apt-get -y update &> /dev/null
        sudo apt-get -y install libsdl1.2debian libcurl3 zlib1g libzip2 &> /dev/null
        sudo apt-get -y clean
    fi

    linappleOk=

    if [[ $DISPLAY ]]; then # X Window
        linappleOk=1
    else # console/framebuffer
        if [[ ! -f /tmp/linapple-consolesetup && ! $(grep 'input' <<< $(groups) ) ]]; then
            sudo groupadd input &> /dev/null
            sudo usermod -a -G input $USER
            echo 'SUBSYSTEM=="input", GROUP="input", MODE="0660"' | sudo tee /etc/udev/rules.d/99-input.rules > /dev/null
            touch /tmp/linapple-consolesetup
        fi

        if [[ -c /dev/fb0 ]]; then
            [[ ! -f /tmp/linapple-consolesetup ]] && linappleOk=1
        else
            if [[ -f /etc/default/grub ]]; then
                if [[ ! $(grep 'GRUB_GFXPAYLOAD_LINUX' /etc/default/grub) ]]; then
                    echo "Preparing LinApple for console use..."
                    sudo sed -i 's/^\(GRUB_CMDLINE_LINUX=.*\)$/\1\nGRUB_GFXPAYLOAD_LINUX=640x480/' /etc/default/grub
                    sudo update-grub &> /dev/null
                    touch /tmp/linapple-consolesetup
                fi
            else
                echo "No framebuffer available. Please run LinApple in an X window."
            fi
        fi
    fi

    if [[ ! $DISPLAY && -f /tmp/linapple-consolesetup ]]; then
        echo "LinApple will be ready for console use after you restart your system."
        echo "You can restart now by typing 'system-restart'."
    elif [[ $linappleOk ]]; then
        cd /usr/local/linapple
        ./linapple
    else
        echo "LinApple has a problem. Please try updating A2CLOUD by"
        echo "typing 'a2cloud-setup'."
    fi

fi
