#!/bin/sh
set -e

usage () {
    echo "usage: git sync-commit-date [-fq]" >&2
    echo >&2
    echo "Rewrites the HEAD commit by setting the commit date to the author date." >&2
    echo >&2
    echo "Options:" >&2
    echo "-f    Don't verify" >&2
    echo "-q    Be quiet" >&2
    echo "-h    Show this help" >&2
    echo >&2
    echo "<commit> defaults to HEAD"
}

verbose=1
force=0
while getopts fqh flag; do
    case "$flag" in
        f) force=1;;
        q) verbose=0;;
        h) usage; exit 2;;
    esac
done
shift $(($OPTIND - 1))

# Enforce we're in a clean work tree
git is-clean -iv

author_date=$(git log --pretty='%aI' -1 HEAD)
commit_date=$(git log --pretty='%cI' -1 HEAD)

if [ "$author_date" = "$commit_date" ]; then
    if [ $verbose -eq 1 ]; then
        echo "Already the same" >&2
    fi
    exit 0
fi

if [ $force = 0 ]; then
    echo "Reset last commit date to $author_date? [yN] " >&2
    read answer
    if [ "$answer" != "y" ]; then
        exit 1
    fi
fi

OLD_SHA=$(git sha -s)
GIT_COMMITTER_DATE="$author_date" git commit --quiet --no-verify --amend --allow-empty -C HEAD

if [ $verbose -eq 1 ]; then
    echo "Created $(git sha -s) (previous was ${OLD_SHA})" >&2
fi
