#!/bin/bash

function file_to_patch {
  echo "--- $1 "
  echo "+++ $1 "
  echo "@@ -1,0 +1,$(wc --lines $1) @@"
  sed 's/^/+/' "$1"
}

function patch_to_file {
  tail -n +4 | sed 's/^.//'
}

kernel_version="$1"

if [ "$1" = "" ]; then
  echo "Error: missing kernel version argument."
  exit 1
fi

if [ "${1#2.6.36}" = "$1" ]; then
  # Exit silently for other kernel versions than 2.6.35.x.
  exit 0
fi

mkdir -p in-tree-patches/"${kernel_version}"

for f in src/orig/"${kernel_version}"/*
do
  g="${f#src/orig/${kernel_version}/}"
  f1="$f"
  f2="src/$g"
  if [ "${f2#src/libsrp.h}" != "${f2}" ]; then
    f2="src/libsrpnew.h${f2#src/libsrp.h}"
  fi
  if [ "${f2#src/srp.h}" != "${f2}" ]; then
    f2="src/srpnew.h${f2#src/srp.h}"
  fi
  if [ "$g" = "Makefile" ]; then
    f2="src/scsi-Makefile${f2#src/Makefile}"
  fi
  f3="in-tree-patches/${kernel_version}/$g.patch"
  if [ "$f1" -nt "$f3" -o "$f2" -nt "$f3" ]; then
    file_to_patch "$f2" | \
      ../scripts/specialize-patch -v kernel_version="$1" \
                                  -v generating_upstream_patch_defined=1 \
                                  -v config_scst_proc_undefined=1 | \
      patch_to_file | \
      diff -up "$f1" - > "$f3"
  fi
done
