#!/bin/bash -e
# Illustrate an edge-case failure for clone/change/push

# error reports
warn() {
  echo $* >&2
}

die() {
  echo $* >&2
  exit -1
}

# make a place to work
create-demo-dir() {

  # first of all, do no harm
  # if you own the system, you might want to just "rm -rf $demo"

  [ -d $demo ] &&
    die "$demo already exists. Remove before running"

  mkdir $demo
  cd $demo
}

# make a bare repo
mkrepo() {
  rm -rf hello*
  mkdir hello
  cd hello
  touch README
  git init
  git add .
  git commit -m"initial"
  cd ~-
  git clone --bare hello
  rm -rf hello
}

# add file to origin repo from a clone
add-to-from() {
  # peel off optional arg
  case $1 in
    -*) args=$1; shift ;;
  esac

  origin_name=$1
  clone_name=${2:-hello}
  mkrepo

  # in case clone is to a subdirectory
  if [ $(dirname $clone_name) != "." ]; then
    mkdir -p $(dirname $clone_name)
  fi

  # clone and add a new file
  git clone $args $origin_name $clone_name
  pushd $clone_name
  touch second-file
  git add .
  git commit -am"add a second file"
  git status

  # now push and watch what happens
  git push
  git status
  popd

  # store away forensic evidence
  if [ $(dirname $clone_name) != "." ]; then
    rm -rf Original-clone
    mv $(dirname $clone_name) Original-clone
  else
    mv $clone_name Original-clone
  fi

  # see if the addition worked
  git clone hello.git
  if [ -f hello/second-file ]; then
    warn "[$FUNCNAME $*]: success"
    rm -rf Original-clone
  else
    warn "[$FUNCNAME $*]: second commit never pushed to origin"
    warn "All evidence is in $demo"
    echo "=== Here's the log of the clone ==="
    cd Original-clone; git log; cd ..
    echo
    echo "=== Here's the log of the origin ==="
    cd hello.git; git log; cd ..
    echo
    die "[$FUNCNAME $*]: FAIL"
  fi
}

demo=/tmp/demo
create-demo-dir
# things that work
add-to-from hello.git hello
add-to-from hello hello2
add-to-from hello workspace/hello

# things that fail because the clone succeeds,
# but the push gets confused and fails silently

add-to-from hello hello
# or
#   add-to-from hello
# or even
#   add-to-from --no-hardlinks hello

rm -rf $demo	# if everything succeeds, this cleans up

exit 0
