#!/bin/bash

set -eux # -x for verbose logging to juju debug-log

## 0k git remote path
GIT_0K_BASE=${GIT_0K_BASE:-"0k-ro:/var/git"}

## 0k git remote options
GIT_0K_CLONE_OPTIONS=${GIT_0K_CLONE_OPTIONS:-""}


apt-get install -y --force-yes kal-shlib-common

apt-get install -y bzr

mkdir -p /var/git
mkdir -p /srv/git-bzr-mirrors

mkdir -p /opt/apps


##
## install git-hooks
##

(
    cd /opt/apps &&
        git clone "$GIT_0K_BASE"/0k/git-hooks.git &&
        git config --system git-hooks.install-dir /opt/apps/git-hooks &&
        ln -sf /opt/apps/git-hooks/bin/git-hooks /usr/lib/git-core/git-hooks
)


##
## bzr-fastimport
##

(
cd /opt/apps &&
bzr clone lp:bzr-fastimport &&
mkdir /root/.bazaar/plugins -p && 
ln -sf /opt/apps/bzr-fastimport /root/.bazaar/plugins/fastimport 
)

## This patch will correct a nasty exception documented here:
##   https://bugs.launchpad.net/bzr/+bug/541626

(cd /opt/apps/bzr-fastimport &&
patch -p0 ) < src/patch/bzr-fastimport/btree-except.patch


##
## python-fastimport
##
 
(
cd /opt/apps &&
bzr clone lp:python-fastimport &&
cd python-fastimport &&
python setup.py install
)


##
## git-bzr-ng
##

(
cd /opt/apps &&
git clone https://github.com/termie/git-bzr-ng.git &&
ln -sf /opt/apps/git-bzr-ng/git-bzr /usr/lib/git-core/
)


##
## git-bzr-syncs
##

(
cd /opt/apps &&
git clone "$GIT_0K_BASE"/0k/git-bzr-syncs.git &&
ln -sf /opt/apps/git-bzr-syncs/bin/git-bzr-syncs /usr/sbin/git-bzr-syncs
)

cp src/etc/cron.daily/git-bzr-syncs /etc/cron.daily/git-bzr-syncs


##
## Setup password-less access for other LXC
##

LXC_USER=lxc-user
LXC_USER_HOME=/var/lib/$LXC_USER

groupadd -r git-users &&
adduser --system --home=$LXC_USER_HOME --shell /bin/bash --ingroup=git-users $LXC_USER &&

mkdir $LXC_USER_HOME/.ssh -p &&
cat src/etc/ssh/lxc_git_access_id_rsa.pub >> $LXC_USER_HOME/.ssh/authorized_keys &&
chown lxc-user $LXC_USER_HOME/.ssh -R