---
version: '3'

vars:
  ROLE_NAME: '{{.GALAXY_NAMESPACE}}.{{.GALAXY_ROLE_NAME}}'

tasks:
  playbook:
    desc: Symlink all the roles in the roles/ folder to ~/.ansible/roles
    summary: |
      # Symlink each role to `~/.ansible/roles/{{.GALAXY_NAMESPACE}}.role_name`

      In the playbook, roles are sometimes referred to by their folder name and in other cases
      they are referred to with their namespace prepended (e.g. `{{.GALAXY_NAMESPACE}}.role_name`).
      This can cause issues so, in order for everything to work, each folder needs to be symlinked
      to `~/.ansible/roles` with the namespace prepended.
    log:
      error: Encountered an error while symlinking the roles
      start: Symlinking all roles in the `roles/` folder to `$HOME/.ansible/roles/`
      success: Successfully symlinked all the roles
    cmds:
      - mkdir -p "$HOME/.ansible/roles"
      - |
        while read ROLE_PATH; do
          ROLE_FOLDER="{{.GALAXY_NAMESPACE}}.$(basename "$ROLE_PATH")"
          if [ ! -d "$HOME/.ansible/roles/$ROLE_FOLDER" ]; then
            rm -rf "$HOME/.ansible/roles/$ROLE_FOLDER"
            ln -sf "$PWD/$ROLE_PATH" "$HOME/.ansible/roles/$ROLE_FOLDER"
          fi
        done < <(find ./roles -mindepth 2 -maxdepth 2 -type d)
        wait
    preconditions:
      - sh: test -d roles
        msg: The roles folder is missing. Is the project set up right?

  role:
    desc: Symlink the current role to ~/.ansible/roles/{{.ROLE_NAME}}
    summary: |
      # Symlink this role to `~/.ansible/roles/{{.ROLE_NAME}}`

      Roles are sometimes referred to by their folder name (which ideally is also the role_name in
      the `{{.META_PATH}}` file) and they are sometimes referred to by their Ansible Galaxy name which
      has the namespace prepended (e.g. `{{.ROLE_NAME}}`). In order to make sure Ansible
      can find the role in both cases, a symlink in `~/.ansible/roles` that points to the folder needs
      to be created.
    log:
      error: There was an error symlinking `{{.ROLE_NAME}}` to `$HOME/.ansible/roles/{{.ROLE_NAME}}`
      start: Symlinking `{{.ROLE_NAME}}` to `$HOME/.ansible/roles/{{.ROLE_NAME}}`
      success: Symlinked `{{.ROLE_NAME}}`
    cmds:
      - mkdir -p "$HOME/.ansible/roles"
      - rm -rf "$HOME/.ansible/roles/{{.ROLE_NAME}}"
      - ln -sf "$PWD" "$HOME/.ansible/roles/{{.ROLE_NAME}}"
