#!/bin/sh

display_usage() {
  echo "This script adds unstaged changes in git matching argument 1."
  echo "\nUsage: $0 [substring] \n"
}

if [ $# -le 0 ]
then
  display_usage
  exit 0
fi

git diff > mydiff

gawk -v pat="$1" '
function hh(){
  if(keep && n > 0){
    for(i=0;i<n;i++){
      if(i==hrn){
        printf "@@ -%d,%d +%d,%d @@\n", har[1],har[2],har[3],har[2];
      }
      print out[i];
    }
  }
}
{
  if(/^diff --git a\/.* b\/.*/){
    hh();
    keep=1;
    dr=NR;
    hrn=-1;
    n=0;
    out[n++]=$0
  }
  else if(NR == dr+1 && /^index [0-9a-f]+\.\.[0-9a-f]+ [0-9]+$/){
    ir=NR;
    out[n++]=$0
  }
  else if(NR == ir+1 && /^\-\-\- a\//){
    mr=NR;
    out[n++]=$0
  }
  else if(NR == mr+1 && /^\+\+\+ b\//){
    pr=NR;
    out[n++]=$0
  }
  else if(/^@@ \-([0-9]+),?([0-9]+)? \+([0-9]+),?([0-9]+)? @@/){
    hh();
    match($0, /^@@ \-([0-9]+),?([0-9]+)? \+([0-9]+),?([0-9]+)? @@/, har)
    keep=0;
    n=0;
    hr=NR;
    hrn=n;
  }
  else if(NR > hr){
    if(/^\-/ && $0 !~ pat){
      har[4]++;
      sub(/^\-/, " ", $0);
      out[n++] = $0
    }
    else if(/^\+/ && $0 !~ pat){
      har[4]--;
    }
    else{
      if(/^[+-]/){
        keep=1
      }
      out[n++] = $0
    }
  }
}
END{
  hh()
}' mydiff > mypatch

git stash save &&
  git apply mypatch &&
  git add -u

