#!/bin/sh

set -e
set -u

GITIT_USER_EMAIL="${GITIT_USER_EMAIL:-}"
GITIT_USER_NAME="${GITIT_USER_NAME:-}"
GITIT_REMOTE_REPOSITORY="${GITIT_REMOTE_REPOSITORY:-}"
GITIT_REMOTE_DOMAIN="${GITIT_REMOTE_DOMAIN:-}"

if [ ! -f /data/gitit.conf ]; then
	echo "Building config for gitit"
  	gitit --print-default-config > /data/gitit.conf

	sed -i 's|default-extension: page|default-extension: md|' /data/gitit.conf
fi

## Check existing variables
if [ -z "$GITIT_USER_EMAIL" ]; then
	>&2 echo "ERROR: Environment variable GITIT_USER_EMAIL not defined"
	exit 1
fi
if [ -z "$GITIT_USER_NAME" ]; then
	>&2 echo "ERROR: Environment variable GITIT_USER_NAME not defined"
	exit 1
fi

# Configure GIT
CUR="$(pwd)"
mkdir -p /data/wikidata
cd /data/wikidata

if [ ! -d /data/wikidata/.git ]; then
	git init
fi
git config diff.renames false

git config --global user.email "$GITIT_USER_EMAIL"
git config --global user.name "$GITIT_USER_NAME"

if [ -n "$GITIT_REMOTE_REPOSITORY" ]; then
	if [ -z "$GITIT_REMOTE_DOMAIN" ]; then
		>&2 echo "ERROR: Environment variable GITIT_REMOTE_DOMAIN not defined"
		exit 1
	fi
	mkdir -p /data/ssh
	if [ ! -f /data/ssh/mirror_rsa ]; then
		>&2 echo "ERROR: SSH Key file /data/ssh/mirror_rsa is missing."
		>&2 echo "       Please create it with 'ssh-keygen -f /data/ssh/mirror_rsa' ."
		exit 1
	fi

	git remote remove origin
	git remote add origin "$GITIT_REMOTE_REPOSITORY"

	mkdir -p /root/.ssh
	cat > /root/.ssh/config <<-MARK
	Host $GITIT_REMOTE_DOMAIN
  	  IdentityFile /data/ssh/mirror_rsa
  	  StrictHostKeyChecking no
	MARK
	chmod 600 /root/.ssh/config
	chmod 700 /root/.ssh
else
	>&2 echo "INFO: Environment variable GITIT_REMOTE_REPOSITORY not defined."
	>&2 echo "      Skipping mirror repository configuration."
fi

cd "$CUR"

if [ "$1" = 'gitit' ]; then
  exec gitit "$@"
fi

exec "$@"