#!/bin/bash
#
# [ -b <backends> ] <debfile>*
shopt -s nullglob

TEMP="$(mktemp -d -p .)"
trap "rm -rf $TEMP" 0 2

die() { echo "** ERROR: $*" ; exit 1 ; }

BACKENDS=
if [ "$1" = "-b" ] ; then
    BACKENDS="-b $2" # replace any ; by space
    shift 2
fi

FIRST=
for DEB in "${@}" ; do
    [ -f "$DEB" ] || die "Unkown deb file: $DEB"
    [ -z "$FIRST" ] && FIRST="${DEB##*/}"
    dpkg -x "$DEB" "$TEMP" || die "Cannot unpack $DEB"
done

export SYSTEMD_UNIT_PATH=$TEMP/usr/lib/systemd/system:$TEMP/lib/systemd/system
readarray -t UNITS <<EOF
$(find ${SYSTEMD_UNIT_PATH//:/ } -type f 2>/dev/null)
EOF

for S in "${UNITS[@]}" ; do
    F="${S##*/}"
    case "${F##*.}" in
	service|socket|timer)
	    ${UNIT_TRANSLATOR:=utrans} $BACKENDS -f overwrite "$S" "$TEMP/out" || \
		die "Failed translating $F"
	    ;;
    esac
done

readarray -t OUT <<EOF
$(find "$TEMP/out" -type f 2>/dev/null)
EOF

[ -z "$OUT" ] && die "Nothing translated"
tar czf "$FIRST-services.tgz" -C "$TEMP/out" "${OUT[@]#$TEMP/out/}"
