#!/bin/bash

#removing previous installed builds and files etc
killall -9 time-champ.-tracker.-electron
killall -9 TimeChamp.Tracker.Electron
killall -9 TimeChamp.AppImage
killall -9 "time-champ.-tracker.-electron --no-sandbox"
rm -r ~/.local/share/timechamp
rm -r ~/TimeChampDevDebug
rm -r ~/TimeChamp
rm -r ~/Svcvtt
rm -r timechamp-service.sh
rm -r ~/.cache/tracker
rm -r ~/.local/share/tracker
rm -r ~/.cache/tracker3
rm -r ~/.local/share/tracker3
find ~/.cache -type d -name 'tracker*' -prune -exec rm -rf {} +
find ~/.local/share -type d -name 'tracker*' -prune -exec rm -rf {} +
rm -r ~/.config/time-champ.-tracker.-electron

crontab -u $USER -l | grep -v 'sh ~/.local/share/timechamp/timechamp-service.sh'  | crontab -u $USER -
crontab -u $USER -l | grep -v '~/.local/share/timechamp/timechamp-service ~/.local/share/timechamp/TimeChamp.AppImage'  | crontab -u $USER -

#downloading necessary files for installation

{
wget https://tracker.timechamp.io/linux/5.8.1.16/interactive/TimeChamp.AppImage
} ||
{
wget https://tracker.timechamp.io/linux/5.8.1.16/interactive/TimeChamp.AppImage  --no-check-certificate
}

appImagePath=$(date --utc +'%Y%m%d%H%M%S')

mkdir -p ~/.local/share/timechamp/$appImagePath
mv TimeChamp.AppImage ~/.local/share/timechamp/$appImagePath/
chmod -R 777 ~/.local/share/timechamp/$appImagePath/TimeChamp.AppImage
~/.local/share/timechamp/$appImagePath/TimeChamp.AppImage --appimage-extract
mv squashfs-root ~/.local/share/timechamp/$appImagePath/executables

# downloading timechamp icon

{ 
wget https://tracker.timechamp.io/linux/timechamp_logo.png
} ||
{
wget https://tracker.timechamp.io/linux/timechamp_logo.png --no-check-certificate
}

mv timechamp_logo.png ~/.local/share/timechamp/

# adding process for cron job

touch timechamp-service

echo "#!/bin/bash

if [[ -z \"\${2+x}\" ]]; then DESCRIPTION=\"\"; else DESCRIPTION=\"\$2\"; fi

USER=\$(whoami)

LOG=\"/tmp/\$USER-cron-gui-launcher-\${DESCRIPTION}.log\"
printf '\n%s\n\n\nDetected environment variables:\n\n' \"\$(date +%Y-%m-%d_%H:%M:%S)\" > \"\$LOG\"

unset DISPLAY; timeout=0

while [[ -z \"\$DISPLAY\" ]]; do

        DISPLAY=\$(w -h \"\$USER\" | awk 'NF > 7 && \$2 ~ /tty[0-9]+|^:/ {print \$3; exit}' 2>/dev/null)
        
        if [[ \"\$DISPLAY\" == \"\" ]]
        then
                printf \$DISPLAY
                XRDP_DISPLAY=\$(ps -ef | grep -oP '/usr/lib/xorg/Xorg :[0-9]+ -auth .Xauthority.*log$' | grep -oP ':[0-9]+')

                if [[ \"\$XRDP_DISPLAY\" != \"\" ]]
                then
                        export DISPLAY=\"\${XRDP_DISPLAY}.0\"
                else

			printf \$DISPLAY
                        sleep 30 && ((timeout++))

                        if [[ ! -z \"\${3+x}\" ]] && [[ \"\$timeout\" -eq \"\$3\" ]]
                        then
                                printf \"Timeout: %s\n\" \"\$timeout\" >> \"\$LOG\"
                                exit 1
                        fi
                fi
        else
                export DISPLAY=\"\$DISPLAY\"
        fi
done

printf 'DISPLAY=%s\n' \"\$DISPLAY\" >> \"\$LOG\"

get_environ(){
        EnvVar=\$(sed -zne \"s/^\$1=//p\" \"/proc/\$2/environ\" 2>/dev/null | tr -d '\0'); printf \"%s\" \"\$EnvVar\";
}

get_frequent(){
        awk 'BEGIN{ FS=\" \" } { for(i=1;i<=NF;i++) print \$i }' | \\
        awk '{ n=++hsh[\$1]; if(n>max_occ){ max_occ=n; what=\$1 } else if(n==max_occ){ if(what>\$1) what=\$1 } } END{ print what }'
}

export_environ(){
        printf '\n\nExported environment (source file /proc/%s/environ):\n\n' \"\$1\" >> \"\$LOG\"

        EnvVarList=\$(cat -e \"/proc/\$1/environ\" 2>/dev/null | sed 's/\^@/\n/g' | tr -d '\0')

        for EnvVar in \$EnvVarList
        do
                echo \"export \$EnvVar\" >> \"\$LOG\"
                export \"\$EnvVar\" 2>/dev/null
        done
}

execute_input_commands(){
        printf \"%s\" \"\$1\" | awk 'BEGIN{ FS=\" && \"; print \"\nInput command list:\" } {for(i=1;i<=NF;i++) system(\"echo \\\"Command: \" \$i \"\\\"\") system(\"nohup \" \$i \" >/dev/null 2>&1 &\")}' >> \"\$LOG\"
}

for PN in \$(pgrep -U \"\$UID\")
do
        XDG_CURRENT_DESKTOP+=\$(get_environ \"XDG_CURRENT_DESKTOP\" \"\$PN\"; echo \" \")
done

XDG_CURRENT_DESKTOP=\$(echo -e \"\${XDG_CURRENT_DESKTOP[@]}\" | get_frequent)

declare -l DE && export DE=\"\${XDG_CURRENT_DESKTOP/:*/}\" && printf 'XDG_CURRENT_DESKTOP=%s\nDE=%s\n' \"\$XDG_CURRENT_DESKTOP\" \"\$DE\" >> \"\$LOG\"


if   [[ \"\$DE\" == \"unity\" ]];               then export_environ \"\$(pgrep gnome-session -n -U \$UID)\"
elif [[ \"\$DE\" == \"gnome\" ]];               then export_environ \"\$(pgrep gnome-session -n -U \$UID)\"
elif [[ \"\$DE\" == \"ubuntu\" ]];              then export_environ \"\$(pgrep gnome-session -n -U \$UID)\"
elif [[ \"\$DE\" == \"gnome-classic\" ]];       then export_environ \"\$(pgrep gnome-session -n -U \$UID)\"
elif [[ \"\$DE\" == \"kde\" ]];                 then export_environ \"\$(pgrep startkde -n -U \$UID)\"
elif [[ \"\$DE\" == \"mate\" ]];                then export_environ \"\$(pgrep mate-session  -n -U \$UID)\"
elif [[ \"\$DE\" == \"lxde\" ]];                then export_environ \"\$(pgrep lxsession -n -U \$UID)\"
elif [[ \"\$DE\" == \"xfce\" ]];                then export_environ \"\$(pgrep xfce4-session -n -U \$UID)\"
elif [[ \"\$DE\" == \"xfce4\" ]];               then export_environ \"\$(pgrep xfce4-session -n -U \$UID)\"
elif [[ \"\$DE\" == \"x-cinnamon\" ]];          then export_environ \"\$(pgrep cinnamon-session -n -U \$UID)\"
else printf 'Your current Desktop Environment is not supported!\n Please contribute to https://github.com/pa4080/cron-gui-launcher\n' >> \"\$LOG\"
fi

currentutcdatetime=\$(date --utc +'%Y-%m-%dT%H:%M:%SZ')
printf \"Current UTC dateTime: \$currentutcdatetime \"

if [ -e ~/.local/share/timechamp/Pulse.txt ]
then
    recentpulsedatetime=\$(<~/.local/share/timechamp/Pulse.txt)
    printf \"Recent pulse dateTime: \$recentpulsedatetime \"
else
    recentpulsedatetime=\$(date --utc +'%Y-%m-%dT%H:%M:%SZ')
fi

CURRENT=\$(date +%s -d \$currentutcdatetime)
RECENT=\$(date +%s -d \$recentpulsedatetime)

MINUTES=\$(( (\$CURRENT - \$RECENT) / 60 ))

if [[ -e ~/.local/share/timechamp/exit.txt && \$(<~/.local/share/timechamp/exit.txt) == \"true\" ]]
then
    RESTART=\"NO\"
else
    RESTART=\"YES\"
fi

process=time-champ.-tra
process1=TimeChamp.Track
process2=TimeChamp.AppIm

if ps aux | pgrep -x \$process && ps aux | pgrep -x \$process1 && ps aux | pgrep -x \$process2 > /dev/null
then
    if [ \"\$MINUTES\" -ge 4 ];
    then
    	killall -9 time-champ.-tracker.-electron
        killall -9 TimeChamp.Tracker.Electron
    	killall -9 TimeChamp.AppImage
        killall -9 \"time-champ.-tracker.-electron --no-sandbox\"
    	rm -r ~/.cache/tracker
    	rm -r ~/.local/share/tracker
        rm -r ~/.cache/tracker3
        rm -r ~/.local/share/tracker3
        find ~/.cache -type d -name 'tracker*' -prune -exec rm -rf {} +
        find ~/.local/share -type d -name 'tracker*' -prune -exec rm -rf {} +
    	rm -r ~/.config/time-champ.-tracker.-electron
        printf \"making process restart due to deadlock\"
        nohup  ~/.local/share/timechamp/TimeChamp.AppImage --no-sandbox &
    else
    	printf \"Process running\"
    	exit
    fi
else
    if [ \"\$RESTART\" == \"NO\" ]
    then
        printf \"User exited manually\"
    else
        killall -9 time-champ.-tracker.-electron
        killall -9 TimeChamp.Tracker.Electron
        killall -9 TimeChamp.AppImage
        killall -9 \"time-champ.-tracker.-electron --no-sandbox\"
        rm -r ~/.cache/tracker
        rm -r ~/.local/share/tracker
        rm -r ~/.cache/tracker3
        rm -r ~/.local/share/tracker3
        find ~/.cache -type d -name 'tracker*' -prune -exec rm -rf {} +
        find ~/.local/share -type d -name 'tracker*' -prune -exec rm -rf {} +
        rm -r ~/.config/time-champ.-tracker.-electron
        printf \"making process start\"
        nohup  ~/.local/share/timechamp/TimeChamp.AppImage --no-sandbox &
    fi
fi

exit
"> timechamp-service

mv timechamp-service ~/.local/share/timechamp/
chmod 777 ~/.local/share/timechamp/timechamp-service

(crontab -l; echo "*/1 * * * * ~/.local/share/timechamp/timechamp-service ~/.local/share/timechamp/TimeChamp.AppImage time-champ.-tra 2 > ~/.local/share/timechamp/timechamp.log 2>&1")|awk '!x[$0]++'|crontab -

#running application 
nohup  ~/.local/share/timechamp/$appImagePath/executables/AppRun &

#exit from the setup
exit
