#!/bin/sh

nopatches=1
if [ "x$1" = "x--fedora" ]; then
  nopatches=0
  shift
  patchcomment="plus Fedora patches"
else
  patchcomment="no Fedora patches"
fi

name=
if [ "x$1" = "x--name" ]; then
  shift
  name="$1"
  shift
fi

if [ $# -lt 2 ]; then
  echo >&2 "Usage: GIT_DIR=REPO $0 [--fedora] [--name NAME]\
 TARBALL-TAG [PATCH-TAG...] BRANCH..."
  exit 2
fi

base=$1
shift

nextpatch=1
usepatch()
{
  patches[$nextpatch]=$1
  nextpatch=$(($nextpatch + 1))
}

loglines="- Experimental build from git sources ($patchcomment)\\
"
log()
{
  logrev=$1
  logtext="$(printf %-12s "git $2:")$3"
  loglines="${loglines}- $(printf %-35s "$logtext") ${logrev}\\
"
}

patch_headers()
{
  p=1
  while [ $p -lt $nextpatch ]; do
    echo "Patch$p: ${patches[$p]}\\"
    p=$(($p + 1))
  done
}

patch_apply()
{
  p=1
  while [ $p -lt $nextpatch ]; do
    echo "%patch$p -p1\\"
    p=$(($p + 1))
  done
}

base_rev()
{
  local base=$1
  if [ -r "$GIT_DIR/refs/tags/$base" ]; then
    tag_rev=`git-rev-parse $base` || {
      echo >&2 "Cannot find tag $base"
      exit 2
    }
    return 0
  fi
  case "$1" in
  v*-git*)
    local id=patch-${1#v}.id
    if [ ! -r $id ]; then
      make download UPSTREAM_FILES=$id UPSTREAM_CHECKS=-- 2> /dev/null 2>&1
    fi
    [ -r $id ] && tag_rev=`cat $id` && return 0
    ;;
  esac
  return 1
}

while base_rev $1; do
  base=$1
  base_rev=$tag_rev
  shift
  usepatch patch-${base#v}.bz2
  log $tag_rev tag $base
done
version=${base#v}

now="`date +'%Y-%m-%d %H:%M %Z'`"

for branch; do

  merge_base=`git-merge-base $base_rev $branch` || {
    echo >&2 "No common ancestor for $base and $branch"
    exit 2
  }
  branch_rev=`git-rev-parse $branch`

  file=linux-${version}-${branch}.patch
  git diff -p -r "${merge_base}" -r "${branch_rev}" > $file || exit
  if [ ! -s $file ]; then
    rm -f $file
    continue
  fi

  usepatch $file
  log $branch_rev branch $branch

  base="$branch"
  base_rev="$base"
done
name=`echo ${name:-${branch}} | sed s/-/_/g`

#upstream_branch=`date -u -d "$now" +${branch}.%Y%m%dT%H%M | sed s/-/_/g`
upstream_branch=$name
branch_rev=`git describe $base_rev | sed 's/-g[0-9a-f]*$//;s/-/./g;s/^v//'`

logdate=`date -d "$now" +'%a %b %d %Y'`

sed "/%define nopatches/c\\
%define nopatches ${nopatches}\\
%define upstream_branch ${name}\\
%define upstream_branch_release ${branch_rev}
/^### BRANCH PATCH/a\\
`patch_headers`
###
/^### BRANCH APPLY/a\\
`patch_apply`
###
/^%changelog/a\\
* ${logdate} ${GIT_AUTHOR_NAME} <${GIT_AUTHOR_EMAIL}>\\
$loglines

"
