#!/usr/bin/env bash
set -Eeuo pipefail

export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

readonly SECRET_ROOT="/mnt/d/NDC_MISSIONCORE/secrets/cvat"
readonly SECRET_FILE="${SECRET_ROOT}/admin.env"

if [[ "${EUID}" -ne 0 ]]; then
  echo "ensure_cvat_admin.sh must run as root" >&2
  exit 2
fi

install -d -m 0700 "${SECRET_ROOT}"
if [[ ! -f "${SECRET_FILE}" ]]; then
  umask 077
  password="$(openssl rand -hex 24)"
  {
    printf 'CVAT_ADMIN_USERNAME=missioncore\n'
    printf 'CVAT_ADMIN_EMAIL=missioncore@local.invalid\n'
    printf 'CVAT_ADMIN_PASSWORD=%s\n' "${password}"
  } >"${SECRET_FILE}"
fi

set -a
# shellcheck disable=SC1090
. "${SECRET_FILE}"
set +a

docker exec \
  -e "CVAT_ADMIN_USERNAME=${CVAT_ADMIN_USERNAME}" \
  -e "CVAT_ADMIN_EMAIL=${CVAT_ADMIN_EMAIL}" \
  -e "CVAT_ADMIN_PASSWORD=${CVAT_ADMIN_PASSWORD}" \
  cvat_server \
  python3 /home/django/manage.py shell -c \
  'import os; from django.contrib.auth import get_user_model; User = get_user_model(); user, _ = User.objects.get_or_create(username=os.environ["CVAT_ADMIN_USERNAME"]); user.email = os.environ["CVAT_ADMIN_EMAIL"]; user.is_staff = True; user.is_superuser = True; user.set_password(os.environ["CVAT_ADMIN_PASSWORD"]); user.save()'

printf 'admin_ready=true\nusername=%s\nsecret_file=%s\n' \
  "${CVAT_ADMIN_USERNAME}" "${SECRET_FILE}"
