#!/bin/bash

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


##
## Options  (changeable thanks to ``/etc/charm/openerp.conf``)
##

export OPENERP_PASSWORD=${OPENERP_PASSWORD:-admin}

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

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

## 0k git-sub setup options
export GIT_0K_SUB_CLONE_OPTIONS=${GIT_0K_SUB_CLONE_OPTIONS:-""}

## 0k git default checkout reference (for 0k-oe root package)
export GIT_0K_CHECKOUT_REF=${GIT_0K_CHECKOUT_REF:-"8.0/0k/dev/master"}


## set only if not already set:
export VIRTUALENV=${VIRTUALENV-/srv/virtualenv/default}

RELEASE=${RELEASE:-}


## debian does not include lsb_release, but it is ok since
## it receives its release info from 0k-odoo-light. But, herk.
test -z "$RELEASE" && export RELEASE=$(lsb_release -c -s)


##
## Code
##

(
    mkdir -p /opt/apps
    cd /opt/apps || exit 1
    if ! [ -d /opt/apps/0k-oe ]; then
    if [ "$ODOO_CP_FROM_DIR" ]; then
        cp -a "$ODOO_CP_FROM_DIR" "/opt/apps/0k-oe"
    else
        apt-get install -y python-pip && pip install shyaml
        git sub clone $GIT_0K_CLONE_OPTIONS $GIT_0K_SUB_CLONE_OPTIONS -b "$GIT_0K_CHECKOUT_REF" \
            "$GIT_0K_BASE"/0k/0k-oe
    fi
    fi &&
    cd 0k-oe/charm &&
    find install.d/ -mindepth 1 -maxdepth 1 -executable -regex 'install.d/[0-9]+-.*' | sort -n |
    while read script; do
        echo "=== LAUNCHING SCRIPT: $script"
        "$script"
        errlvl=$?
        echo "=== EXIT OF SCRIPT: $script, ERRLVL: $errlvl"
        if [ "$errlvl" != 0 ]; then
            exit 1
        fi
    done
) || exit 1