#!/bin/bash
# edit the control data of a deb file,
# usually to get round a dependency problem
# adapted from http://ubuntuforums.org/showthread.php?t=636724
# needs libnotify-bin for notifications if used without a terminal

# choose your editor:
EDITOR=geany

####################

[[ "$1" ]] ||  { echo "Syntax: $0 debfile" >&2; exit 1; }

DEBFILE="$1"
TMPDIR=$(mktemp -d /tmp/deb.XXXXXXXXXX) || exit 1
OUTPUT="${DEBFILE%.deb}".modfied-$( date +%FT%T ).deb

if [[ -e "$OUTPUT" ]]; then
  echo "$0: $OUTPUT exists." >&2
  rm -r "$TMPDIR"
  exit 1
fi

dpkg-deb -x "$DEBFILE" "$TMPDIR"
dpkg-deb --control "$DEBFILE" "$TMPDIR"/DEBIAN
CONTROL="$TMPDIR"/DEBIAN/control
[[ -e "$CONTROL" ]] || {
  echo "$0: DEBIAN/control not found in $1." >&2
  [ -t 1 ] || notify-send "$1: DEBIAN/control not found."
  rm -r "$TMPDIR"
  exit 1
}

MOD=$(md5sum "$CONTROL")
$EDITOR "$CONTROL"

if [[ $MOD = $(md5sum "$CONTROL") ]]; then
  [ -t 1 ] && echo "Not modfied."
else
  [ -t 1 ] && echo "Building new deb..." || notify-send "Building new deb..." "Please wait a moment."
  dpkg -b "$TMPDIR" "$OUTPUT"
  [ -t 1 ] && echo "Built new debfile: $OUTPUT" || notify-send "Built new debfile:" "$OUTPUT"
fi

rm -r "$TMPDIR"
exit