#!/bin/bash

export BASE_HREF=localhost:24817

wait_for_pulp() {
  unset CREATED_RESOURCE
  local task_url=$1
  while [ -z "$CREATED_RESOURCE" ]

  do
    sleep 1
    export CREATED_RESOURCE=$(http $BASE_ADDR$task_url | jq -r '.created_resources | first')
  done
}




# Start by creating a new repository named "foo":
http POST $BASE_ADDR/pulp/api/v3/repositories/ name=foo

# If you want to copy/paste your way through the guide,
# create an environment variable for the repository URI.
export REPO_HREF=$(http $BASE_ADDR/pulp/api/v3/repositories/ | \
  jq -r '.results[] | select(.name == "foo") | ._href')

# Lets inspect our newly created repository.
http $BASE_ADDR$REPO_HREF





# Create a remote that syncs some versions of django into your repository.
http POST $BASE_ADDR/pulp/api/v3/remotes/ansible/collection/ \
    name='bar' \
    url='https://galaxy-dev.ansible.com/api/v2/collections/testing/ansible_testing_content'

sleep 1

# Export an environment variable for the new remote URI.
export REMOTE_HREF=$(http $BASE_ADDR/pulp/api/v3/remotes/ansible/collection/ | jq -r '.results[] | select(.name == "bar") | ._href')

# Lets inspect our newly created Remote
http $BASE_ADDR$REMOTE_HREF






# Distributions are created asynchronously. Create one, and specify the publication that will
# be served at the base path specified.
export TASK_URL=$(http POST $BASE_ADDR/pulp/api/v3/distributions/ansible/ansible/ \
  name='baz' \
  base_path='foo' \
  repository=${REPO_HREF} | jq -r '.task')

# Poll the task (here we use a function defined in docs/_scripts/base.sh)
# When the task is complete, it gives us the href for our new Distribution
wait_for_pulp $TASK_URL
export DIST_PATH=${CREATED_RESOURCE[0]}

# Lets inspect the Distribution
http $BASE_ADDR$DIST_PATH
