#! /bin/bash
set -e

KPATCHDIR=/usr/src/kernel-patches
FORMAT='%-20s%-10s%-10s%-12s%s\n'

ARCH=$(dpkg-architecture -qDEB_HOST_ARCH)

DIRS_ALL_ALL=$(ls -d ${KPATCHDIR}/all/apply 2>/dev/null || true)
DIRS_ARCH_ALL=$(ls -d ${KPATCHDIR}/*/apply 2>/dev/null | grep -v "^${KPATCHDIR}/all/" || true)
DIRS_ALL_VERS=$(ls -d ${KPATCHDIR}/all/*/apply 2>/dev/null || true)
DIRS_ARCH_VERS=$(ls -d ${KPATCHDIR}/*/*/apply 2>/dev/null | grep -v "^${KPATCHDIR}/all/" || true)

# Note: additional "echo $()" calls used to strip spurious spaces

dhkp_kversions()
{
    echo $(grep ^KVERSIONS $1 | sed 's/^.*(\(.*\))$/\1/')
}

dhkp_version()
{
    local rcs=$(echo $(grep -F 'apply.tmpl $''Revision:' $1 | cut -d'$' -f2 | cut -d: -f2))
    local dhkp=$(grep ^DHPKPATCHES_VERSION= $1 | cut -d= -f2)
    if [ -n "${dhkp}" ]
    then
	# post-woody
	echo ${dhkp}
    elif [ -n "${rcs}" ]
    then
	# woody era
	echo "RCS ${rcs}"
    else
	echo '<not built using dh-kpatches>'
    fi
}

format()
{
    printf ${FORMAT} "$1" "$2" "$3" "$(dhkp_version $1)" "$(dhkp_kversions $1)"
}

# Header
printf ${FORMAT} PatchID Arch KVers dhkpVers dhkp-KVers


for dir in ${DIRS_ALL_ALL}
do
    (
	cd ${dir}
	for kp in $(ls)
	do
	    format ${kp} 'all' 'all'
	done
    )
done

for dir in ${DIRS_ARCH_ALL}
do
    (
	arch=$(basename $(dirname ${dir}))
	cd ${dir}
	for kp in $(ls)
	do
	    format ${kp} ${arch} 'all'
	done
    )
done


for dir in ${DIRS_ALL_VERS}
do
    (
	vers=$(basename $(dirname ${dir}))
	cd ${dir}
	for kp in $(ls)
	do
	    format ${kp} 'all' ${vers}
	done
    )
done


for dir in ${DIRS_ARCH_VERS}
do
    (
	vers=$(basename $(dirname ${dir}))
	arch=$(basename $(dirname $(dirname ${dir})))
	cd ${dir}
	for kp in $(ls)
	do
	    format ${kp} ${arch} ${vers}
	done
    )
done
