#! /bin/bash

set -e

PATCHES=debian/patches/features/all/grsec/

repository="$1"
version="$2"

if [[ -z "$version" ]]; then
  # By default, pick upstream version from debian/changelog
  pkgversion=$(dpkg-parsechangelog -SVersion)
  version=${pkgversion%-*}
fi

if [[ ! -d "$repository" || -z "$version" ]]; then
    echo >&2 "Usage: $0 <repository> <version>"
    exit 2
fi
filename="unofficial-grsec-minipli-${version}.patch"
fullname="${PATCHES}/${filename}"

GIT_DIR="$repository/.git" git diff "v${version}..v${version}-unofficial_grsec" > ${fullname}

## Small snippets for easy Debian porting
# localversion depends on the featureset
filterdiff -p1 \
  -x "localversion-grsec" \
  -X <(awk '!(/^#/||/^$/) { printf("%s*\n",$2) }' debian/patches/debian/dfsg/files-1) \
  "$fullname" |sponge "$fullname"

# sched_autogroup_enabled is set to 0 in Debian
sed -i 's/sysctl_sched_autogroup_enabled = 1/sysctl_sched_autogroup_enabled = 0/' "$fullname"

## Update patch name in series
sed -i "s#unofficial-grsec-minipli-.*.patch#${filename}#" debian/patches/series-grsec
