#!/bin/sh

set -e

# Create ~/.config/debusine/client/config.ini to connect to debusine-server
# available in localhost
# Create a new token and writes the config.ini

debusine_client_config_directory=~/.config/debusine/client
mkdir --parents "$debusine_client_config_directory"

admin_user="test-admin"
# shellcheck disable=SC2024
sudo -u debusine-server debusine-admin create_user "$admin_user" \
  admin@example.com > "$AUTOPKGTEST_TMP"/test-admin-password.txt
admin_token_client=$(
  sudo -u debusine-server debusine-admin create_token "$admin_user"
)

contributor_user="test-contributor"
# shellcheck disable=SC2024
sudo -u debusine-server debusine-admin create_user "$contributor_user" \
  contributor@example.com > "$AUTOPKGTEST_TMP"/test-contributor-password.txt
contributor_token_client=$(
  sudo -u debusine-server debusine-admin create_token "$contributor_user"
)

cat << EOF > "$debusine_client_config_directory/config.ini"
[General]
default-server = integration-test-admin

[server:integration-test-admin]
api-url = https://$(hostname -f)/api
scope = debusine
token = $admin_token_client

[server:integration-test-contributor]
api-url = https://$(hostname -f)/api
scope = debusine
token = $contributor_token_client
EOF

# Give owner permission on the default workspace to the test admin user
sudo -u debusine-server debusine-admin group create debusine/Admins
sudo -u debusine-server debusine-admin workspace grant_role \
  debusine/System owner Admins
sudo -u debusine-server debusine-admin group members debusine/Admins \
  --add "$admin_user"

# Give contributor permission on the default workspace to the test
# contributor user
sudo -u debusine-server debusine-admin group create debusine/Contributors
sudo -u debusine-server debusine-admin workspace grant_role \
  debusine/System contributor Contributors
sudo -u debusine-server debusine-admin group members debusine/Contributors \
  --add "$contributor_user"
