#!/bin/bash

ci_dir="/home/django/third-party/scripts/src"
ci_data_dir="/home/django/third-party/scripts/data"


coop=$1
instance=$2
#move to the third argument
shift
shift

send_mails=true

#https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash
while [[ "$#" -gt 0 ]]; do
    case $1 in
        -n|--nomail) send_mails=false ;;
        *) echo "arguments : ${coop} ${instance} $1 not supported (Unknown parameter passed: $1)"
          if ${send_mails}; then
            python3 "${ci_dir}/send_error_mail.py" "arguments : ${coop} ${instance} $1 not supported (Unknown parameter passed: $1)"
          fi
          exit 1 ;;
    esac
    shift
done

if ! python3 "${ci_dir}/supported_coops.py" "${coop}" "${instance}"; then
  echo "arguments : ${coop} ${instance} not supported"
  if ${send_mails}; then
    python3 "${ci_dir}/send_error_mail.py" "arguments : ${coop} ${instance} not supported"
  fi
  exit 1
fi

now=$( date +%Y%m%d_%H%M%S )

source "${ci_dir}/prepare_mail.sh"
source "${ci_dir}/update_instance.sh"

if [[ "${instance}" == "preprod" ]]; then
  repo="third-party"
  echo "Prepare mail" "${coop}" "${instance}" "${repo}" "${now}" "${send_mails}" "${ci_dir}" "${ci_data_dir}"
  prepare_mail "${coop}" "${instance}" "${repo}" "${now}" "${send_mails}" "${ci_dir}" "${ci_data_dir}"|| exit 1

  repo="Odoo"
  echo "Prepare mail" "${coop}" "${instance}" "${repo}" "${now}" "${send_mails}" "${ci_dir}" "${ci_data_dir}"
  prepare_mail "${coop}" "${instance}" "${repo}" "${now}" "${send_mails}" "${ci_dir}" "${ci_data_dir}" || exit 1
fi

repo="third-party"
echo "Update instance" "${coop}" "${instance}" "${repo}" "${now}" "${send_mails}" "${ci_dir}" "${ci_data_dir}"
update_instance "${coop}" "${instance}" "${repo}" "${now}" "${send_mails}" "${ci_dir}" "${ci_data_dir}" || exit 1

repo="Odoo"
echo "Update instance" "${coop}" "${instance}" "${repo}" "${now}" "${send_mails}" "${ci_dir}" "${ci_data_dir}"
update_instance "${coop}" "${instance}" "${repo}" "${now}" "${send_mails}" "${ci_dir}" "${ci_data_dir}" || exit 1

if [[ "${instance}" == "preprod" ]] && ${send_mails}; then
    python3 "${ci_dir}/send_mail.py" "${ci_data_dir}/ci_diff_third-party_${now}.txt" "${ci_data_dir}/ci_diff_Odoo_${now}.txt" "${coop}"
fi
