#!/usr/bin/env bash

{{ includeTemplate "universal/profile" }}
{{ includeTemplate "universal/logg" }}

### Symlink the variables / files / inventories to ~/.config/ansible folders if they are present
### i.e. Changes to upstream will not impact the play if your configuration files are stored locally
for TARGET in "files" "group_vars" "host_vars" "inventories" "templates"; do
  if [ -d "$HOME/.config/ansible/$TARGET" ] && [ "$(readlink -f "$HOME/.local/share/ansible/$TARGET")" != "$HOME/.config/ansible/$TARGET" ]; then
    logg 'Symlinking Ansible playbook `'"$TARGET"'` to ~/.config/ansible/$TARGET'
    rm -f "$HOME/.local/share/ansible/$TARGET"
    ln -s "$HOME/.config/ansible/$TARGET" "$HOME/.local/share/ansible/$TARGET"
  fi
done

### Symlink tasks as well
### Note: Only handles tasks one level deep (i.e. ~/.config/ansible/tasks/my-task.yml will link to the tasks folder
### but ~/.config/ansible/tasks/directory/my-other-task.yml will not)
if [ -d "$HOME/.config/ansible/tasks" ]; then
  find "$HOME/.config/ansible/tasks" -type f | while read TASK_FILE; do
    TASK_FILE_NAME="$(echo "$TASK_FILE" | sed 's/.*\/\([^\/]*\)$/\1/')"
    if [ "$(readlink -f "$HOME/.local/share/ansible/tasks/$TASK_FILE_NAME")" != "$TASK_FILE" ]; then
      ln -s "$TASK_FILE" "$HOME/.local/share/ansible/tasks/$TASK_FILE_NAME"
    fi
  done
fi
