#!/bin/bash

set -e

ask_yn () {
  (set +e
    local tries yn
    echo "$@"
    for tries in {1..3}; do
      read yn
      case $yn in
        ([Yy]*) return 0;;
        ([Nn]*) return 1;;
        (*) echo "Enter yes or no";;
      esac
    done
    echo "No clear response -- taking that as a no"
    return 1
  )
}

get_sha_and_log () {
    git show --abbrev-commit --pretty=oneline $1 | head -1
}




if (( $# < 2 )) || [[ $1 == -h ]]; then
    echo "Usage: $0 <commitish> <new parents>..."
    exit 2
fi



commit=$(git rev-parse $1)
shift
parents=( $(git rev-parse "$commit^" "$@") )

log_parents=()

for parent in ${parents[*]}; do
    log_parents+=( "$(get_sha_and_log $parent)" )
done

log_commit=$(get_sha_and_log $commit)

echo "Graft: the parents of"
printf "\t\`$log_commit'\n"
echo "will be:"
printf "\t\`%s'\n" "${log_parents[@]}"

if ask_yn 'Is that OK?'; then
    printf "# %s\n" "$log_commit" \
                    '^' \
                    '|' \
                    "${log_parents[@]}" >> info/grafts
    echo "$commit ${parents[*]}" >> info/grafts
    echo "Done."
    echo "Run \`git-filter-branch -- --all  &&  rm -rf refs/original' to commit to your changes and rewrite history."
fi
