#!/bin/sh

set -e

# Avoid perl warnings about unknown locale
LC_ALL=C
export LC_ALL

info() {
    logger -t edu-etcvcs "info: $*"
}

error() {
    logger -t edu-etcvcs "error: $*"
}

commit() {
    info "Running etcinsvk commit"
    if [ -x /target/usr/sbin/etcinsvk ] ; then
	in-target /usr/sbin/etcinsvk commit || true
    elif [ -x /target/usr/sbin/etckeeper ] ; then
	in-target /usr/sbin/etckeeper \
	    commit "Automatic commit during installation" || true
    fi
}

init() {
    info "Installing and running etcinsvk init"
    if [ -x /target/usr/sbin/etcinsvk ] ; then
	if in-target /usr/sbin/etcinsvk info | grep -q "Status: enabled" ; then
	    return
	fi
    elif [ -x /target/usr/sbin/etckeeper ] && [ -d /target/etc/.git ]; then
	return
    fi
    apt-install etcinsvk || true
    if [ -x /target/usr/sbin/etcinsvk ] ; then
	if in-target /usr/sbin/etcinsvk init ; then
	    :
	else
	    info "Running etcinsvk init failed"
	fi
    else
	apt-install etckeeper || true
	if [ -x /target/usr/sbin/etckeeper ] ; then
	    if in-target /usr/sbin/etckeeper init ; then
		:
	    else
		info "Running etckeeper init failed"
	    fi
	else
	    error "Unable to install and enable etcinsvk and etckeeper"
	fi
    fi
}

case "$1" in
    init)
	init
	;;
    commit)
	commit
	;;
esac
