#!/bin/bash -

# FILE="/tmp/post-merge$(date +%FT%H-%M-%S)"
# commit=$(git rev-parse --verify HEAD)
# echo "$commit $(git cat-file commit $commit)" >> /tmp/post-merge

# Redirect output to stderr.
exec 1>&2

if [ -z $IFS ]; then
    IFS=$'\n'
fi

GIT_PULL_TMP=/tmp/git_pull
OPKG_CMDS_TMP=/tmp/opkg_commands

rm -f $GIT_PULL_TMP
rm -f $OPKG_CMDS_TMP

get_blob () {   # get the blob of the file(name) passed as $1
                # note: this can be used for any file in the filesystem
    echo $(git hash-object $1)
}

get_commit_for_blob () {
    blob=$(get_blob $1)
    if [ ! -z $blob ]; then
        # search for the blob in all commits for the file(name) $1
        echo $(echo $(git log --all --pretty=format:%H -- $1) |
               xargs -I{} bash -c "git ls-tree {} -- $1       |
               grep -q $blob && echo {}")
    fi
}

changed_file_names () {
    for fn in $(git diff-tree -r HEAD@{1} HEAD --name-only); do
        CHANGED_FILE_NAMES+=($fn)
    done
}

# write_git

for fn in $(git diff-tree -r HEAD@{1} HEAD --name-only); do
    if grep -E -q "(DC.*json|dc.*hex|dc.*bin|tariff.*json)" <<< $fn; then
        fsize=0
        if [[ -f "$fn" ]]; then
            fsize=$(ls -l "$fn" | awk '{ print $5 }')
        fi
        echo "$fn $fsize" >> $GIT_PULL_TMP
    fi
    if grep -E -q ".*opkg_commands" <<< $fn; then
        readarray opkg_commands < <(cat $fn)
        for opkg_c in "${opkg_commands[@]}"; do
            test -z $opkg_c && continue;
            test ! -z $(grep -E "^\s*[#]+.*$" <<< $opkg_c) && continue
            echo -n "$opkg_c" | tr -d '\n\r' >> $OPKG_CMDS_TMP 2>&1
            echo "" >> $OPKG_CMDS_TMP 2>&1
        done
        source "$fn"
    fi
done