#!/bin/sh
set -e

# cache directory
CD=/var/cache/etckeeper

# Get config
conf="$ETCKEEPER_CONF_DIR/etckeeper-origin.conf"

if [ -e $conf ]; then
    . $conf
fi
if [ -z "$ORIGIN" ]; then
    ORIGIN=origin
fi
CDO="$CD/$ORIGIN"

if [ -z "$ETCKEEPER_DIR" ]; then
    echo "etckeeper-origin cant work without ETCKEEPER_DIR variable, exiting..." >&2
    exit 1
fi


# Check that rpmnew files exists and all changes already committed
FILES=`find $ETCKEEPER_DIR -name '*.rpmnew'`
if [ -z "$FILES" ]; then
    exit 0
fi

if etckeeper unclean; then
    echo "etckeeper-origin cant work with uncommitted changes, exiting..." >&2
    exit 1
fi

# Make temporary copy of rpmnew files
mkdir -p $CDO                  # it is possible to override CD in conf
rsync -am --del --include='*.rpmnew' -f 'hide,! */' $ETCKEEPER_DIR/ $CDO/
for i in `find $CDO -type f`;do mv $i ${i/.rpmnew/};done

# Main work
BRANCH=`git branch |grep -E '^\*'|head -1|cut -d' ' -f2`
if git branch|grep -F $ORIGIN >/dev/null 2>&1; then
    git checkout -q $ORIGIN
else
    git checkout -q -b $ORIGIN
fi
rsync -am $CDO/ $ETCKEEPER_DIR/

if etckeeper unclean; then
    if etckeeper commit "Saving new original config files"; then
        git checkout -q $BRANCH
        for i in "$FILES";do rm -f $i;done # Remove rpmnew from master
        rm -rf $CDO
    else
	echo "error: etckeeper failed to commit changes in /etc using $VCS"
	exit 1
    fi
fi
