#!/bin/bash

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

export DEBIAN_FRONTEND=noninteractive LANG=en_US.UTF-8

##
## Code
##

## we need ssh because git needs it.
DEPS="sudo"
DEPS_TO_REMOVE="git"
[ "$NO_SSH" ] || DEPS_TO_REMOVE="$DEPS_TO_REMOVE ssh"

KEEP_ONLY_PO=${KEEP_ONLY_PO:-fr en de}

apt-get install -y --force-yes --no-install-recommends \
    $DEPS $DEPS_TO_REMOVE

## XXXvlab: should use base-0k code instead !
## ======= BEGIN OF DUPLICATE CODE... well it has been modified =======
##
## ssh config
##
## 0k git remote path
GIT_0K_BASE=${GIT_0K_BASE:-"git.0k.io:/var/git"}

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


if [ -z "$NO_SSH" ]; then

    cp ../base-0k/src/etc/ssh/lxc_git_access_id_rsa /etc/ssh/lxc_git_access_id_rsa
    chmod 0600 /etc/ssh/lxc_git_access_id_rsa

    mkdir -p /root/.ssh

    cat <<EOF > /root/.ssh/config

Host git.0k.io
    User lxc-user
    IdentityFile /etc/ssh/lxc_git_access_id_rsa
    UserKnownHostsFile /dev/null
    StrictHostKeyChecking no
    Port 10022

EOF

fi


##
## install git sub
##


if [ -z "$ODOO_CP_FROM_DIR" ]; then
    (
        mkdir -p /opt/apps &&
        cd /opt/apps &&
        git clone $GIT_0K_CLONE_OPTIONS "$GIT_0K_BASE"/0k/git-sub &&
        ln -sf /opt/apps/git-sub/bin/git-sub /usr/lib/git-core/
    )
fi

## ===================== END OF DUPLICATE CODE ===========

(cd ../0k-openerp
RELEASE=jessie VIRTUALENV= hooks/install
)

apt-get remove -y --force-yes $DEPS_TO_REMOVE
apt-get autoremove -y

rm -rf /opt/apps/git-sub /usr/lib/git-core/git-sub


find /opt/apps -name .git -type d -exec rm -rf {} \; -prune

if [ "$KEEP_ONLY_PO" ]; then
    find_args=""
    for lang in $KEEP_ONLY_PO; do
        find_args="$find_args -not -name $lang.po"
    done

    find /opt/apps -name \*.po -type f $find_args -delete
fi

cat <<EOF > /root/.0k-oe.rc

PYTHON_BINARY=/usr/bin/python

EOF