#!/bin/dash
# convert a .deb to slackware txz package
# jamesbond 2015, 2018, 2019, 2020 MIT license
# Note: requires undeb, slackdesc and makepkg

### configuration
WORKDIR=/tmp/deb2txz
PKGARCH=${PKGARCH:-x86_64}
PKGVER=${PKGVER:-1.0}
PKGBUILD=${PKGBUILD:-DEB}
PKGTYPE=${PKGTYPE:-txz}

### cleanup handler
trap 'rm -rf $WORKDIR; exit $STATUS' 0 INT HUP TERM

usage() {
	cat << EOF
Usage: ${0##*/} [-n|--noscript] package.deb
       -n | --noscript = do not include postinst/postrm scripts
EOF
	exit
}

### main
NO_SCRIPT=
for p; do
	case "$p" in
		-h|--help)      usage         ;;
		-n|--noscript)  NO_SCRIPT=yes ;;
		*) SRC="$p" ;;
	esac
done

### parse package name
PKGPATH="$(readlink -f "$SRC")"
TARGETDIR="${PKGPATH%/*}"
PKG="${SRC##*/}"; PKG=${PKG%.deb}
echo $PKG

### temporary pkg-component names
OIFS="$IFS"; IFS="_"; set -- $PKG; IFS="$OIFS"
[ $1 ] && PKGNAME=$1
[ $2 ] && PKGVER=$2
[ $3 ] && PKGARCH=$3

### bail out on errors
STATUS=1
set -e

### extract package content
mkdir -p $WORKDIR/$$; cd $WORKDIR/$$
undeb "$PKGPATH" .
chmod 755 . # some package are stupid like that, so fix it

### extract control file, and get proper pkg name version arch
mkdir control
undeb -e "$PKGPATH" ./control
if [ -e ./control/control ]; then
	while read -r p; do
		case "$p" in
			Package:*) PKGNAME=${p#Package: } ;;
			Architecture:*) PKGARCH=${p#Architecture: } ;;
			Version:*) PKGVER=${p#Version: } ;;
		esac
	done < ./control/control
fi
PKGVER=$(echo "$PKGVER" | sed 's/-/_/g')

### generate slack-desc
mkdir install
if type slackdesc > /dev/null; then
	slackdesc "$PKGNAME" "$PKGVER" "(Converted Debian Package)" \
		"Converted Debian/Ubuntu package from $PKG.deb" \
		> install/slack-desc \
	|| echo "${0##*/}: WARNING: Unable to create package description." 1>&2
fi

### copy install scripts, if exist and asked
if [ -z "$NO_SCRIPT" ]; then
	if [ -e control/postinst ]; then
		mv control/postinst install/doinst.sh
		chmod -x install/doinst.sh
	fi
	if [ -e control/postrm ]; then
		mv control/postrm install/slack-uninstall.sh
		chmod -x install/slack-uninstall.sh
	fi
fi
rm -r control

### done, create the package
makepkg -c n -l n "$TARGETDIR/$PKGNAME-$PKGVER-$PKGARCH-$PKGBUILD.$PKGTYPE"

### return success if we get here
STATUS=0

