#!/bin/bash

maybe_git=
if [[ $1 = -g || $1 = --git ]]; then
    maybe_git=git
    shift
elif [[ $1 = -h || $1 = --help ]]; then
    echo "Usage: $(basename "$0") [--git] [<PATCHES>]"
fi

patches=("$@")
shopt -s nullglob
if [[ ! ${patches[@]} ]]; then
    patches=(*.patch *.diff)
fi

for patch in "${patches[@]}"; do
    if [[ $patch = *~* ]]; then
        echo "* skipping $patch because it already has the hash"
        continue
    fi
    patch_base=${patch%.diff}
    if [[ $patch_base != $patch ]]; then
        extension=diff
    else
        # 'patch' will be the default extension even if the patch doesn't have a recognized one
        patch_base=${patch%.patch}
        extension=patch
    fi
    patch_base=${patch_base%-}  # get rid of trailing `-` if it exists
    hash=$(< "$patch" git patch-id --stable | cut -b -7)
    if [[ $hash ]]; then
        new_patch="${patch_base}~${hash}.${extension}"
        echo -n "$new_patch … "
        if $maybe_git mv -f "$patch" "$new_patch"; then
            echo "ok"
        else
            echo "FAIL"
        fi
    else
        echo "* skipping $patch because I couldn't get the hash"
        continue
    fi
done
