#!/bin/bash

# Création de raccourcis de menus pour les applications embarquées
# (copie aussi les icones)
#
# Pour installer une application embarquée:
# 1) ltsp-chroot -m apt-get install <monapplication>
# 2) ${0}
# 3) ltsp-update-image

DEBUG=0

if [ $DEBUG -ne 0 ];then
    echo "DEBUG actif $DEBUG"
fi

#Exclude these
EXCLUDED=(debian-uxterm debian-xterm mpv python2.7 python3.5 smplayer_enqueue vim)

source /etc/ltsp/ltsp-build-client.conf

#should end with /
CHROOT=${BASE}/${CHROOT}/
SHORTCUTS_DIR=/usr/share/applications/
ICONS_DIR=/usr/share/pixmaps/

is_exclude(){
    for exclude in ${EXCLUDED[*]};do
        if [ "$1" = "$exclude" ];then
            return 1
        fi
    done
    return 0
}

copy_and_set_shortcuts(){
    shortcut="${1}"
    iconfile="${2}"
    #Copy shortcut to root
    cp $CHROOT$SHORTCUTS_DIR$shortcut $SHORTCUTS_DIR
    #Add "ltsp-localapps" prefix to Exec line
    sed -i "s/Exec=/Exec=ltsp-localapps /" $SHORTCUTS_DIR$shortcut
    # Add "(local)" suffix to default Name
    sed -i "s/Name=\(.*\)$/Name=\1 (local) /" $SHORTCUTS_DIR$shortcut
    #...and Name in all Languages
    sed -i "s/Name\[\(.*\)\]=\(.*\)$/Name\[\1\]=\2 (local) /" $SHORTCUTS_DIR$shortcut
    #Copy icon if $iconfile is defined
    if ! [ -z $iconfile ];then
        cp $iconfile $ICONS_DIR
    fi
}

for shortcut_app in ${CHROOT}${SHORTCUTS_DIR}/*desktop;do
    #Get the programme name
    progname=$(basename "${shortcut_app}");
    is_exclude ${progname[@]/%.desktop/}
    if [ $? -eq 0 ];then
        #Get icon name
        progicon=$(grep -i icon= "${shortcut_app}");
        iconname=${progicon#Icon=}
        #We want just the first if there is more than one icon
        iconfile=$(ls ${CHROOT}${ICONS_DIR}/*${progname[@]/%.desktop/}* 2>/dev/null |head -n1)
        if [ -z ${iconfile} ];then
            if  [ $DEBUG -ne 0 ];then
                echo "No icon in ${CHROOT}${ICONS_DIR} for ${progname}"
            fi
            copy_and_set_shortcuts ${progname}
        else
            if [ $DEBUG -ne 0 ];then
                echo ${iconname}" "${iconfile}
            fi
            copy_and_set_shortcuts ${progname} ${iconfile}
        fi
    fi
done

