#!/bin/bash -e

aufs_dir="$1"

export GIT_DIR="$aufs_dir/.git"

from_line='From: J. R. Okajima <hooanon05@yahoo.co.jp>'
if [ -d "$GIT_DIR" ]; then
    origin_line="Origin: http://sourceforge.net/p/aufs/aufs3-standalone/ci/$(git rev-list HEAD -1)/tree/"
else
    echo >&2 "W: Cannot include a specific origin URL without an aufs git repo"
    origin_line='Origin: http://sourceforge.net/p/aufs/aufs3-standalone/ref/master/branches/'
fi
bug_line='Bug-Debian: https://bugs.debian.org/541828'

for patch in aufs3-{base,kbuild,mmap,standalone}.patch; do
    {
	echo "$from_line"
	if [ -d "$GIT_DIR" ]; then
	    git log --pretty='Date: %ad' HEAD -1 -- "$patch"
	fi
	echo -n 'Subject: '
	head -1 "$aufs_dir/$patch"
	echo "$origin_line"
	echo "$bug_line"
	echo
	echo 'Patch headers added by debian/patches/features/all/aufs3/gen-patch'
	echo
	sed 's/^+.*EXPORT_SYMBOL\b/&_GPL/' < "$aufs_dir"/"$patch"
    } > debian/patches/features/all/aufs3/"$patch"
done

{
    echo "$from_line"
    if [ -d "$GIT_DIR" ]; then
	git log --pretty='Date: %ad' HEAD -1
    fi
    sed -rn 's/^#define AUFS_VERSION[[:space:]]+"(.*)"/Subject: aufs\1/p' \
	< "$aufs_dir/include/uapi/linux/aufs_type.h"
    echo "$origin_line"
    echo "$bug_line"
    echo
    echo 'Patch generated by debian/patches/features/all/aufs3/gen-patch'
    echo
    cd "$aufs_dir" &&						\
	{ find Documentation fs -type f;			\
	  echo include/uapi/linux/aufs_type.h; } |		\
	LC_ALL=C sort |						\
	while read file; do
	    diff -uN a/"$file" "$file" | filterdiff --addnewprefix=b/
	done
} > debian/patches/features/all/aufs3/aufs3-add.patch
