#!/bin/ash
# Fatdog64 Default Programs
# Copyright (C) SFR 2016
#
# License: GNU GPL Version 3 or later

# =============================================================================

# std localisation stanza
export TEXTDOMAIN=fatdog
. gettext.sh

# performance tweak - use "C" if there is no localisation
! [ -e $TEXTDOMAINDIR/${LANG%.*}/LC_MESSAGES/$TEXTDOMAIN.mo ] &&
! [ -e $TEXTDOMAINDIR/${LANG%_*}/LC_MESSAGES/$TEXTDOMAIN.mo ] && LANG=C

### configuration
APPTITLE="$(gettext 'Fatdog64 Default Programs')"
MYEXEC="$(readlink -f "$0")"
DEFAULT_PROGRAMS_GLOBAL="/etc/defaultprograms"
DEFAULT_PROGRAMS_LOCAL="${FATDOG_STATE_DIR}/defaultprograms"
HARDSPACE="$(echo -ne '\xc2\xa0')"

# -----------------------------------------------------------------------------

. "${DEFAULT_PROGRAMS_GLOBAL}"
if [ -e "${DEFAULT_PROGRAMS_LOCAL}" ]; then
. "${DEFAULT_PROGRAMS_LOCAL}"
fi

MENU=$(set | grep '^DEF_' | ( while read ITEM; do
  NAME="$(echo "${ITEM#*_}" | cut -f1 -d "=")"
  CMD="$(echo "${ITEM#*_}" | cut -f2 -d "'")"
  CMD="${CMD:- }"
  echo "${NAME} ${CMD// /${HARDSPACE}}"	# replace spaces with hard spaces in CMD, for Xdialog
done))

NAME=$(Xdialog --stdout --title "${APPTITLE}" --menu "$(gettext 'Edit default programs:')" 16 48 16 ${MENU})
[ $? -ne 0 ] && exit

CMD="$(set | grep ^DEF_${NAME}= | cut -f2 -d "'")"
RESULT="$(Xdialog --stdout --title "${APPTITLE}" --inputbox $NAME 0 0 "${CMD}")"
case $? in
  1)	exec "$MYEXEC"	;;
  255)	exit	;;
esac

RESULT="$(echo "$RESULT" | tr -d "&*()<>'\"\`")"	# trim problematic chars
eval DEF_${NAME}="${RESULT// /${HARDSPACE}}"
NEWDEFAULTS="$(set | grep '^DEF_')"
echo "${NEWDEFAULTS//${HARDSPACE}/ }" > "${DEFAULT_PROGRAMS_LOCAL}"

exec "$MYEXEC"

# =============================================================================
