#!/usr/bin/env bash
set -e

script=$(basename "$0")
version="1.1.1"

help() {
    echo
    echo "$script"
    echo
    echo 'Description: Install Odoo database in Docker container.'
    echo "Syntax: $script [-c|-d|-i|-l|-w|-V|help]"
    echo 'Example: $script -c odoo01 -d erp -i hr,note -l de_CH -w'
    echo 'options:'
    echo '  -c    Docker container. Defaults to '\''odoo'\''.'
    echo '  -d    Database name.'
    echo '  -i    List of odoo modules to install.'
    echo '  -l    Odoo language. Defaults to '\''en_US'\''.'
    echo '  -w    With demo data.'
    echo "  -V    Show $script version."
    echo "  help  Show $script manual."
    echo
}

if [[ "$1" == 'help' ]]; then
    help
    exit
fi

with_demo='--without-demo=all'
container=odoo
odoo_language=en_US

while getopts ':c: :d: :i: :l: :w :V' opt; do
    case $opt in
        c) container="$OPTARG";;
        d) database="$OPTARG";;
        i) modules="$OPTARG";;
        l) odoo_language="$OPTARG";;
        w) with_demo='--with-demo';;
        V) echo "$script version $version"
        exit 0
        ;;
        \?) echo "Invalid option -$OPTARG" >&2
        help
        exit;;
    esac
done

[[ -z "$database" ]] && { echo 'Parameter -d|database is empty.' ; exit 1; }
[[ -z "$modules" ]] && { echo 'Parameter -i|init is empty.' ; exit 1; }

container_id=$(docker ps -f "name=${container}" -q | head -n1)
[[ -z "$container_id" ]] && { echo "Container id for $container not found." ; exit 1; }

echo "Initializing modules $modules with langague $odoo_language on database $database."
docker exec $container_id /bin/bash -c "
unset ODOO_ADDONS_PATH
unset ADDONS_PATH
odoo -i $modules -d $database --db_host=\$PGHOST --db_user=\$PGUSER --db_password=\$PGPASSWORD $with_demo --load-language $odoo_language --stop-after-init --no-http
"

echo 'Modules initialized. Please restart the Odoo container/process.'
