#!/bin/bash
# Initialiser la base de données avec le compte prédéfini pgadmin@domain et un mot de passe aléatoire (doit être changé dans ead3 pour commencer à utiliser l’application

. /usr/lib/eole/ihm.sh

PGADMIN_DB=/var/lib/pgadmin/pgadmin4.db
PGADMIN_ADMIN_NAME="pgadmin@$(CreoleGet nom_domaine_local)"
PGADMIN_ADMIN_PASSWORD="$(pwgen -n1 30)"

function pinned_version {
    package=$1
    pinning_file="$(grep -xl "Package: $package" /etc/apt/preferences.d/*)"
    echo "$(sed -e '/Pin: version/!d' -e 's/Pin: version \(.*\)/\1/' $pinning_file)"
}

function pgadmin_uptodate {
    for package in pgadmin4-server pgadmin4-web
    do
        if [ "$(dpkg-query -f '${Version}' -W $package)" != "$(pinned_version $package)" ]
        then
            EchoOrange "Traitement de la base de pgadmin4 reportée après prochaine mise à jour : versions de paquet non conforme"
            return 1
        fi
    done
    return 0
}

function db_need_init {
    if [ -e $PGADMIN_DB ]
    then
      admin_user="$(/usr/pgadmin4/venv/bin/python3 /usr/share/eole/sbin/pgadmin-tool user show 1 --by_id -a username)"
      if [ "$admin_user" != "$PGADMIN_ADMIN_NAME" ]
      then
        return 0
      else
        return 1
      fi
    else
      return 0
    fi
}

if pgadmin_uptodate && db_need_init
then
  rm -f $PGADMIN_DB
  cd /usr/pgadmin4/web
  PGADMIN_SETUP_EMAIL="$PGADMIN_ADMIN_NAME" PGADMIN_SETUP_PASSWORD="$PGADMIN_ADMIN_PASSWORD" /usr/pgadmin4/bin/setup-web.sh --yes
fi

exit 0
