#!/usr/bin/env bash
#  vim:ts=4:sts=4:sw=4:et
#
#  Author: Hari Sekhon
#  Date: Mon Feb 22 17:42:01 2021 +0000
#
#  https://github.com/HariSekhon/DevOps-Bash-tools
#
#  License: see accompanying Hari Sekhon LICENSE file
#
#  If you're using my code you're welcome to connect with me on LinkedIn and optionally send me feedback to help steer this or other code I publish
#
#  https://www.linkedin.com/in/HariSekhon
#

# ============================================================================ #
#                                  D i r E n v
# ============================================================================ #

# https://direnv.net/man/direnv-stdlib.1.html

# See Also:
#
#   .envrc-aws
#   .envrc-gcp
#   .envrc-kubernetes

# direnv stdlib - loads .envrc from parent dir up to /
#
# useful to accumulate parent and child directory .envrc settings eg. adding Kubernetes namespace, ArgoCD app etc.
#
# bypasses security authorization though - use with care
#source_up
#
# source_up must be loaded before set -u otherwise gets this error:
#
#   direnv: loading .envrc
#   /bin/bash: line 226: $1: unbound variable
#
# source_up causes this error is up .envrc is found in parent directories:
#
#   direnv: No ancestor .envrc found

set -euo pipefail
[ -n "${DEBUG:-}" ] && set -x
src="$(readlink -f "${BASH_SOURCE[0]}")"
srcdir="$(cd "$(dirname "$src")" && pwd)"

# ============================================================================ #
#                              P r e - C o m m i t
# ============================================================================ #

# Automatically install Pre-Commit Git hooks if not already present

if ! type -P pre-commit &>/dev/null; then
    if uname -s | grep -q Darwin &&
       type -P brew &>/dev/null; then
        echo
        echo "Pre-commit is not installed - installing now using Homebrew..."
        echo
        brew install pre-commit
        echo
    elif type -P pip &>/dev/null; then
        echo
        echo "Pre-commit is not installed - installing now using Pip..."
        echo
        pip install pre-commit
    fi
fi

if [ -f .pre-commit-config.yaml ] &&
   type -P pre-commit &>/dev/null &&
   git rev-parse --is-inside-work-tree &>/dev/null; then
    hook="$(git rev-parse --show-toplevel)/.git/hooks/pre-commit"
    if [ -L "$hook" ]; then
        echo "Detected symlink hook: "
        echo
        ls -l "$hook"
        echo
        echo "Removing"
        rm -f "$hook"
    fi
    if ! [ -f "$hook" ]; then
        echo
        echo "Pre-commit hook is not installed in local Git repo checkout - installing now..."
        echo
        pre-commit install
    fi
fi

# ============================================================================ #
#                          D o c k e r   C o m p o s e
# ============================================================================ #

export COMPOSE_PROJECT_NAME="bash-tools"

# ============================================================================ #
#                                  G i t H u b
# ============================================================================ #

#export GITHUB_ORGANIZATION=HariSekhon

# ============================================================================ #
#                                 A n s i b l e
# ============================================================================ #

# use the local repo's ansible.cfg rather than:
#
#   $PWD/ansible.cfg
#   ~/.ansible.cfg
#   /etc/ansible/ansible.cfg
#
# set this in project repos to ensure user environment ANSIBLE_CONFIG doesn't get used
#export ANSIBLE_CONFIG="/path/to/ansible.cfg"

# ============================================================================ #
#                              C l o u d f l a r e
# ============================================================================ #

#export CLOUDFLARE_EMAIL=hari@...
#export CLOUDFLARE_API_KEY=...  # generate here: https://dash.cloudflare.com/profile/api-tokens
#export CLOUDFLARE_TOKEN=...    # used by cloudflare_api.sh but not by terraform module

# export the variables for terraform
#export TF_VAR_cloudflare_email="$CLOUDFLARE_EMAIL"
#export TF_VAR_cloudflare_api_key="$CLOUDFLARE_API_KEY"  # must be a key, not a token using the link above

# ============================================================================ #
#                   Load External Envrc Files If Present
# ============================================================================ #

# XXX: safer to bring all these external .envrc inline if you're worried about changes
#      to it bypassing 'direnv allow' authorization
load_if_exists(){
    # first arg is a path to a .envrc
    # all other args are passed to the sourcing of .envrc - used by .envrc-kubernetes
    # to pass the context name 'docker-desktop' to switch to
    local envrc="$1"
    shift
    if ! [[ "$envrc" =~ ^/ ]]; then
        envrc="$srcdir/$envrc"
    fi
    if [ -f "$envrc" ]; then
        # prevent looping on symlinks to this .envrc if given
        if [ "$(readlink "$envrc")" = "$src" ]; then
            return
        fi
        echo
        echo "Loading $envrc"
        # shellcheck disable=SC1090,SC1091
        . "$envrc" "$@"
    fi
}

# don't do this it may lead to an infinite loop if 'make link' symlinking ~/.envrc to this repo's .envrc
# (which I do to keep Python virtual automatically loaded at all times because recent pip on Python refuses
# to install to system Python)
#load_if_exists ~/.envrc

# ============================================================================ #
#                                  P y t h o n
# ============================================================================ #

#for envrc in \
#    .envrc-aws \
#    .envrc-gcp \
#    .envrc-terraform \
#    .envrc-python \
#    ; do
#    load_if_exists "$envrc"
#done

load_if_exists .envrc-python

# ============================================================================ #
#                                    J a v a
# ============================================================================ #

load_if_exists .envrc-java

# ============================================================================ #
#                                     A W S
# ============================================================================ #

#if [[ "$PWD" =~ /aws/ ]]; then
    load_if_exists .envrc-aws
#fi

# ============================================================================ #
#                                     G C P
# ============================================================================ #

#if [[ "$PWD" =~ /gcp/ ]]; then
    load_if_exists .envrc-gcp
#fi

# ============================================================================ #
#                               T e r r a f o r m
# ============================================================================ #

#if [[ "$PWD" =~ /(terra(form)?|tf)(/|$) ]]; then
    load_if_exists .envrc-terraform
#fi

# ============================================================================ #
#                              K u b e r n e t e s
# ============================================================================ #

#if [ -f "$srcdir/.envrc-kubernetes" ]; then
    load_if_exists .envrc-kubernetes docker-desktop
#fi

# ============================================================================ #
#                                    . E n v
# ============================================================================ #

echo
# read .env too
#dotenv

load_if_exists .envrc.local
