#!/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
type = "Backend"
module = "executor"
name = "$backend_name"
interface = "legacy1"
action_id = "org.altlinux.alterator.legacy1"

[methods.Info]
execute = "cat $file"
stdout_bytes = true
exit_status  = true
action_id = "Info"

[methods.Run]
execute = "/usr/sbin/alterator-standalone $modname"
stderr_strings = true
exit_status    = true
timeout = 0

[methods.Run.environment.DISPLAY]
[methods.Run.environment.XAUTHORITY]
EOF

done
