#!/bin/bash -e

backends_dir="/etc/alterator/backends"
legacy_dir="/usr/share/alterator/applications"
prefix="autogenerated-legacy-"

[ -d "$backends_dir" ] || exit 0
[ -w "$backends_dir" ] || exit 0
[ -d "$legacy_dir" ] || exit 0

find "$backends_dir" -name "${prefix}*.backend" -type f -print0 | xargs -0 rm -f '{}'

find "$legacy_dir" -name '*.desktop' | while read file; do
	filename=$(basename $file)
	modname="${filename%.*}"
	backend_name="$(echo "$modname" | tr "-" "_")"
	backend_path="$backends_dir/$prefix$modname.backend"

	cat >"$backend_path" <<EOF
[Alterator Entry]
Type = Backend
Module = executor
Name = $backend_name
Interface = legacy1
action_id = ru.basealt.alterator.legacy1

[Info]
execute = cat $file
stdout_bytes = enabled
action_id = Info

[Run]
execute = /usr/sbin/alterator-standalone $modname
stderr_strings = enabled
timeout = 0
EOF

done
