#!/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 etckeeper commit"
    if [ -x /target/usr/bin/etckeeper ] ; then
        in-target /usr/bin/etckeeper \
            commit "Automatic commit during installation" || true
    fi
}

init() {
    if [ -x /target/usr/bin/etckeeper ] && [ -d /target/etc/.git ]; then
        # Already installed and initialised
        return
    fi
    if [ ! -x /target/usr/bin/git ]; then
        apt-install git || true
    fi
    # Configure git to prevent messages about the default branch
    OLD_DEFAULTBRANCH=$(in-target --pass-stdout git config get --global init.defaultBranch || true)
    in-target git config set --global init.defaultBranch main
    # The postinst of etckeeper initialises /etc/.git
    apt-install etckeeper || true
    # Restore the original git configuration
    if [ -z ${OLDDEFAULTBRANCH} ]; then
        in-target git config unset --global init.defaultBranch
    else
        in-target git config set --global init.defaultBranch "${OLD_DEFAULTBRANCH}"
    fi
    # If this was a fresh installation, $HOME was not set and the configuration file is empty
    if [ ! -s /target/.gitconfig ]; then
        rm -f /target/.gitconfig
    fi
    if [ -x /target/usr/bin/etckeeper ] ; then
        echo -e "#!/bin/sh\ncd /etc\ngit config user.name \"STOP! Use 'etckeeper commit' instead\"" > /target/set_git_username.sh
        chmod a+x /target/set_git_username.sh
        in-target /set_git_username.sh
        rm -f /target/set_git_username.sh
    else
        error "Unable to install and enable etckeeper"
    fi
}

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