#!/bin/bash

set -e

apt_get_tmpcache () {
  local _opt=$1

  mkdir -p "${TMPDIR}/cachedir" "${TMPDIR}/statedir"
  # shellcheck disable=SC2086
  DEBIAN_FRONTEND='noninteractive' apt-get -o dir::cache="${TMPDIR}/cachedir" \
    -o dir::state="${TMPDIR}/statedir" -o dir::etc::sourcelist="$debsrcfile" \
    -o dir::etc::sourceparts=/dev/null $_opt
}

prepare_translations () {
  # Preparing translation files for Git: ngcp-panel.git/lib/NGCP/Panel/I18N/*
  debsrcfile="${TMPDIR}/upload_translations.list"

  apt-get install -y dpkg-dev

  cp /etc/apt/sources.list.d/sipwise.list "$debsrcfile"
  sed -i 's/#deb-src/deb-src/' "$debsrcfile"
  apt_get_tmpcache "update"
  cd "${TMPDIR}"
  apt_get_tmpcache "source ngcp-panel"

  cd "${TMPDIR}"/ngcp-panel*/
  git init
  git add lib/NGCP/Panel/I18N/* lib/NGCP/Panel/Utils/DbStrings.pm
  git commit -m 'Snapshot before translation'
  ./script/extract_i18n.sh

  rm -f ./lib/NGCP/Panel/I18N/*.po~
  tar -czf /var/tmp/i18n.tar.gz lib/NGCP/Panel/I18N/*
}

TMPDIR=$(mktemp -d -t ngcp-prepare-transl-XXXXXXXXXX)

start_seconds=$(cut -d . -f 1 /proc/uptime)

echo "Preparing ngcp-panel translations..."
prepare_translations

[ -n "$start_seconds" ] && SECONDS="$(( $(cut -d . -f 1 /proc/uptime) - start_seconds))" || SECONDS="unknown"
echo "Preparing ngcp-panel translations took $SECONDS seconds."

# remove retrieved and generated files
rm -rf "${TMPDIR}"
