#!/bin/sh

set -e

ODOO_ROOT_DIR=${ODOO_ROOT_DIR:-'/opt/odoo'}
SAVE_COMMITS_DIR=${SAVE_COMMITS_DIR:-'/opt/odoo_commits'}
SAVE_COMMITS_FILENAME=${SAVE_COMMITS_FILENAME:-'custom_addons'}

save_commit() {
  repo="$1"
  commit="$2"
  module="$3"
  dst="$4"
  echo "${repo};${commit};${module};${dst}" >> "${SAVE_COMMITS_DIR}/${SAVE_COMMITS_FILENAME}"
}

repo="$1"
shift
ref="$1"
shift
dst="$1"
shift
modules="$@"

git clone --filter=tree:0 "${repo}" /tmp/repo
git -C /tmp/repo checkout "${ref}"
commit="$(git -C /tmp/repo rev-parse HEAD)"
if [ -n "$modules" ]; then
  for module in $modules; do
    mv "/tmp/repo/${module}" "${ODOO_ROOT_DIR}/${dst}/"
    save_commit "$repo" "$commit" "$module" "$dst"
  done
else
  module="$(basename $dst)"
  mkdir -p "/${ODOO_ROOT_DIR}/${dst}"
  mv /tmp/repo/* "${ODOO_ROOT_DIR}/${dst}/"
  save_commit "$repo" "$commit" "$module" "$dst"
fi
rm -r /tmp/repo