#!/bin/sh
# find . -type f -name appimagesetup.sh -print | xargs xgettext -o appimagkit.pot -L Shell --keyword --keyword=gettext
export TEXTDOMAIN="appimagekit"
export TEXTDOMAINDIR="/usr/share/locale"

    # plans
    # appimaged start in debug mode
    # appimage destiny settings by user
    #notify-send -u critical -t 14000 -i dialog-error "AppImage Daemon" "An error occured while tried starting appimaged!"
    #notify-send -u critical -t 14000 -i dialog-question "AppImage Daemon" "An error occured while tried starting appimaged!"

case $LANG in
    hu*)
    DIRNAME="Alkalmazások"
    ;;
    de*)
    DIRNAME="Anwendungen"
    ;;
    *)
    DIRNAME="Applications"
    ;;
esac
export PATH=$PATH:/usr/bin
xmsg=$(which pydialog 2>/dev/null || which kdialog 2>/dev/null)

runchk () {
    state=$(ps ux | grep -v grep | grep appimaged)
    if [ -n "$state" ];then
	RUN=OK
     else 
        RUN=NO
    fi

}

notice () {
    runchk
    if [ "$RUN" = "NO" ];then
	notify-send -u critical -t 14000 -i dialog-warning "$(gettext 'AppImageKit Daemon')" \
	"$(gettext 'An error occured while tried starting appimaged!')"
     else
	APPDIR=$(ls -la $HOME | grep AppImages | grep '\->' | awk '{print $9}' | head -n 1)
	notify-send -u normal -t 10000 -i dialog-information "$(gettext 'AppImageKit Daemon')" \
	"$(gettext 'Service is started!<br>AppImage Monitor is active here:<br>') $HOME/$APPDIR"
    fi

}

setup () {
    runchk
    if [ "$RUN" != "OK" ];then
	exec /usr/bin/appimaged &
    fi
    sleep 10
    notice
}


first () {
notify-send -u critical -t 14000 -i dialog-question "$(gettext 'AppImageKit First Start')" \
"$(gettext 'Creating directory for AppImages! Now opening') '$DIRNAME' $(gettext 'directory...<br>[your lockfile: ~/.appimagesetup] ')"
sleep 5
mkdir -p $HOME/.AppImages
if [ ! -f $HOME/.AppImages/.directory ];then
cat > $HOME/.AppImages/.directory <<EOF
[Desktop Entry]
Icon=folder-downloads
EOF
fi


if [ ! -f $HOME/$DIRNAME ]&& [ ! -L $HOME/$DIRNAME ];then
    ln -sf $HOME/.AppImages $HOME/$DIRNAME
else
    $xmsg --title "$(gettext 'Error')" \
    --error "$(gettext '<h2>AppImageKit Warning!</h2><br> This') $HOME/$DIRNAME $(gettext 'folder is already exists! <br>Check this dir, rename, delete or move for AppImage use')"
    chmod +x $HOME/$DIRNAME/* 2>/dev/null
fi
touch $HOME/.appimagesetup
xdg-open $HOME/$DIRNAME
setup

}

if [ ! -f "$HOME/.appimagesetup" ];then
    $xmsg --title "$(gettext 'AppImageKit')" \
    --msgbox "$(gettext '<h2>AppImageKit First Start!</h2>Your AppImage folder now:') $HOME/$DIRNAME $(gettext '<br>Just drag and drop *.AppImage file there to easy installation')"
    first
else
    setup 
fi
