#!/bin/bash
MYTH_RUN_STATUS="1"
. /etc/profile
. /etc/systemconfig


#set some defaults, then override from /etc/X11/WINDOWMANAGER
configdir="/usr/share/wm_data"
WM="e16 -P $configdir/e16_config_dir/"
STARTUP_STYLE=enhanced


if [ -e /etc/X11/WINDOWMANAGER ]
then
    . /etc/X11/WINDOWMANAGER
fi

xhost +local:
xhost +127.0.0.1
xset -dpms s off

export MALLOC_CHECK_=0

MYTH_ARGS="-d --syslog local6"
[ -f /etc/conf.d/mythfrontend ] && . /etc/conf.d/mythfrontend




function msg(){
    /usr/LH/bin/msg_client.py --msg "$1"
}


function unclutter(){
    if [ -e /etc/unclutter.cfg ]
    then
        . /etc/unclutter.cfg
    else
        idle=1
        jitter=200
    fi
    echo "Starting unclutter"
    /usr/bin/unclutter -root -idle $idle -jitter $jitter -noevents  &
}


function keylaunch(){
    if [ -f /usr/bin/keylaunch ]
    then
        if [ ! -z $HOME ] && [ ! -e $HOME/.keylaunchrc ]
        then
            echo "setting symlink for keylaunch"
            ln -s /etc/keylaunchrc $HOME/.keylaunchrc
        fi

        echo "Checking if keylaunch is running"
        if [ "$(pidof keylaunch)" ]
        then
            echo "keylaunch is already running"
        else
            echo "Starting keylaunch"
            /usr/bin/keylaunch &
        fi
    fi

}


function fluxbox_settings(){
    if [ ! -e $HOME/.fluxbox ]
    then
        echo "setting symlink fluxbox"
        configdir=/usr/share/fluxbox_settings
        ln -s $configdir $HOME/.fluxbox
    fi
}


function load_nvidia_settings(){
    lsmod |cut -f1 -d" " |grep -q nvidia
    if [ $? = 0 ]
    then
        /usr/bin/nvidia-settings --load-config-only
    fi
}

function run_tilda(){
    if [ -f /usr/bin/tilda ]
    then
        if [ ! -e  ~/.config/tilda/config_0 ]
        then
            mkdir -p ~/.config/tilda/
        fi

        width=`/usr/bin/xwininfo -root|grep Width | awk '{ print $2}'`
        height=`/usr/bin/xwininfo -root|grep Height | awk '{ print $2}'`
        center=$[width/2]
        tilda_width=`echo "scale=0; ( $width*.9) / 1" |bc`
        tilda_height=`echo "scale=0; ($height*.4) /1" |bc`

       if [ $tilda_width -lt 700 ]
       then
             tilda_width=700
        fi

       if [ $tilda_height -lt 350 ]
       then
             tilda_height=350
        fi

        startloc=`echo "scale=0 ; (${center}-(${tilda_width})/2) / 1" |bc`

        sed -e "s/^max_width.*$/max_width = $tilda_width/" \
            -e "s/^max_height.*$/max_height = $tilda_height/" \
            -e "s/^x_pos.*$/x_pos = $startloc/g" /etc/tilda_config > ~/.config/tilda/config_0

        /usr/bin/tilda -h &
    fi
}


function mouse_move(){
    #move mouse to corner
    xdotool mousemove 0 0
}


function start_screensaver(){
    if [ x"$Screensavertype" = "xgscreensaver" ]
    then
        gnome-screensaver &
    elif  [ x"$Screensavertype" = "xxscreensaver" ]
    then
        xscreensaver  -no-splash &
    fi
}


function show_help_tip(){
    if [ x$ShowTips = "x1" ]
    then
        msg "Alt+h for help"
    fi
}


function notify_scan(){
    if [ -e /tmp/scan_report ]
    then
        msg "\nNew storage found. \nRun add_storage.py for details"
    fi
}


function auto_start(){
    asdir="/etc/X11/autostart"
    for i in `ls $asdir/*`
    do
        if [ -x $i ]
        then
            echo "Starting $i"
            $i &
        fi
    done
}


function update_apple_trailers(){
    #update apple trailers
    if [[ x$RunFrontend = x1 && -f ~/.configure ]]
    then
        /usr/bin/php -q /usr/bin/myth_trailers_grabber > $HOME/appletrailer.xml && /usr/bin/fix_aple_url.sh 2>/dev/null &
    fi
}


function first_mythwelcome_config(){
     echo "First configure: Running mythwelcome-config.py"
    /usr/LH/bin/mythwelcome-config.py
}


function first_configure(){
    if [ ! x$STARTUP_STYLE = xlegacy ]
    then
        first_configure_mv
    else
        first_configure_default
    fi
}


function first_configure_default(){
    echo "First configure: legacy..."
    if [ !  $SystemType = "Frontend_only" ]
    then
        if [  -f ~/.configure ]
        then
            # Run Tweaker, which applies generic and hardware-specific settings
            if [ ! -f ~/.no_meth ]
            then
                #remove tweaker cause it's broken and duplicates entries
                #sudo -E tweaker.pl
                #/bin/rm /tmp/fps # ??? clean up a temp file that will eventually be obsolete anyway
                # Run any brand-specific commands, if necessary.
                SpecialHardwareCommands
            else
                rm -f ~/.no_meth
            fi
            first_mythwelcome_config
            sudo sv stop mythbackend
            xterm -fn *18* -e sudo taskset -c 0 /usr/bin/mythtv-setup
            sudo sv start mythbackend
            sudo chown -R mythtv.mythtv /home/mythtv
            # only run mythfilldatabase for masterbackends
            if [ $SystemType = "Master_backend" ]
            then
                nice -n 19 mythfilldatabase --quiet &
                msg "Guide data is being loaded.\nUntil this completes\nsome shows will appear as unknown\nin the program guide."
            fi
            rm ~/.configure
        fi
    else
        if [  -f ~/.configure ]
        then
            rm -f  ~/.configure
        fi
    fi
}


function first_configure_mv(){
    echo "First configure..."
    if [ !  $SystemType = "Frontend_only" ]
    then
        if [  -f ~/.configure ]
        then
            msg "New install of LinHES; starting setup."
            #for now skip these
            #autocard.py -g &
            #MythVantage -b
            #0 yes
            #1 yes/autodetech
            #2  no
            first_mythwelcome_config
            while [ -e '/var/run/autocard.lock' ]
            do
                msg "Waiting for capture card detection to complete..."
                sleep 5
            done
            STATUS=$?
            if [ ! $STATUS = 2 ]
            then
                    /usr/MythVantage/bin/backend_control.sh stop BE 127.0.0.1
                    msg "MythTV setup is starting.\nPlease follow the steps for adding tuners and guide data."
                    run_wmctrl &
                    /usr/bin/taskset -c 0 /usr/bin/mythtv-setup
                    /usr/MythVantage/bin/backend_control.sh start BE 127.0.0.1
            fi
            # only run mythfilldatabase for masterbackends
            if [ $SystemType = "Master_backend" ]
            then
                nice -n 19 mythfilldatabase --quiet &
                msg "Guide data is being loaded.\nUntil this completes\nsome shows will appear as unknown\nin the program guide."
            fi
            rm -f ~/.configure
        fi
    else
        if [  -f ~/.configure ]
        then
            rm  -f ~/.configure
        fi
    fi
}


function start_myth() {
    if [ x"$UseMythWelcome" = "x1" ]
    then
        STARTCMD="/usr/bin/mythwelcome"
    else
        STARTCMD="/usr/bin/mythfrontend $MYTH_ARGS"
    fi

    echo "====================================================================="
    echo "Starting $STARTCMD"
    if [ "x$bewait" = "x1" ]
    then
        #do init check
        /usr/LH/bin/be_check.py
        rc=$?
        while [ $rc -ne 0 ]
        do
            msg "Waiting for connection to MythBackend"
            sleep 6
            /usr/LH/bin/be_check.py
            rc=$?
            if [ $rc -eq 0 ]
            then
                msg "Successful Connection to MythBackend"
            fi
        done
        sleep 3 #give time for MBE to be fully operational
    fi

    #continue on with starting mythtv
    if [ ! x$STARTUP_STYLE = xlegacy ]
    then
        start_myth_mv
    else
        run_myth
    fi
}


function run_wmctrl(){
    done="False"
    for i in `seq 60`
    do
        for name in "MythTV Frontend" "MythTV Setup" "mythwelcome"
        do
            xwininfo -name "$name" >/dev/null
            rcx=$?
            if [ $rcx = 0 ]
            then
                wmctrl -r "$name" -b remove,fullscreen
                done="True"
            fi
        done
        if [ $done = "True" ]
        then
            break
        fi
        sleep 5
    done
}


function run_myth(){
    if [ -f /tmp/nomfe ]
        then
            msg "MythFrontend will not start because /tmp/nomfe exists."
            wait $pid
            exit 0
        else
            if [ -f /tmp/debug ]
            then
                echo "using gbd/debug"
                gdb /usr/bin/mythfrontend -x $MV_ROOT/mfegdbcommands.txt
                mv gdb.txt gdb.txt.mythfrontend
                sleep 5
            else
                if [ ! x$STARTUP_STYLE = xlegacy ]
                then
                    run_wmctrl &
                    $STARTCMD 2>&1
                else
                    $STARTCMD 2>&1 &
                fi

            fi
        fi
}


function start_myth_mv(){
    while [ x = x ]
    do
        run_myth
        echo "_______________________________________________________"
    done
}


function set_background()
{
    echo "Setting the background"
}


function stop_plymouth()
{
    #pause plymouthd and continue in /etc/sv/frontend/finish
    pidfile=/run/plymouth.pid
    if [ -e "$pidfile" ]; then
        plypid=`cat "$pidfile"`
        if [ -n "$plypid" ]; then
            sudo kill -s STOP "$plypid"
        fi
    fi
}

function machine-id_check()
{
    if [ ! -s /etc/machine-id ]
    then
        echo "Setting machine ID in /etc/machine-id"
        sudo systemd-machine-id-setup
    fi
}


if [ x"$WM" = "fluxbox" ]
then
    fluxbox_settings
fi


#if using mythvantage style, start the WM right away
# this is done so that starting mythtv can loop.
$WM &
pid=$!
mouse_move
keylaunch
unclutter
load_nvidia_settings
run_tilda
start_screensaver
notify_scan &
auto_start &
update_apple_trailers
stop_plymouth &
machine-id_check &
first_configure
show_help_tip
start_myth

# wait for the  windowmanger
#This will make the session wait on the WM to exit.
if [  x$STARTUP_STYLE = xlegacy ]
then
    wait $pid
fi


wmctrl -r "MythTV Frontend" -b remove,fullscreen