#!/bin/bash

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


coop=$1
instance=$2 #(prod not supported for now)
#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}/update_code.sh"

repo="third-party"
echo "START PROCESS" "${coop}" "${instance}" "${repo}" "${now}"
update_code "${coop}" "${instance}" "${repo}" "${now}" "${send_mails}" || exit 1
echo "DONE"

repo="Odoo"
echo "START PROCESS" "${coop}" "${instance}" "${repo}" "${now}"
update_code "${coop}" "${instance}" "${repo}" "${now}" "${send_mails}" || exit 1
echo "DONE"

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
