#!/usr/bin/env bash

# Adapted from https://github.com/ThePrimeagen/dev/blob/master/run
#
# Installs packages declared in the 'runs' directory, will run scripts matching the
# file name in the 'runs/before' and 'runs/after', respectively, to handle setting up or
# tearing down based on the run mode.
#
set -e
set -o nounset
set -o pipefail

THIS_FILE=${BASH_SOURCE[0]}
LOG_LABEL=$(basename $THIS_FILE)
LOG_FILE=${LOG_FILE:-"$LOG_LABEL.log"}

declare dry_run grepstr mode

log() {
	logging log --source "$THIS_FILE" --echo "$@"
} && export -f log

############################## MAIN ##############################

# Setup logging file and label.
source "$SCRIPTS/hypr/logging"
setup-logging "$LOG_FILE" "$LOG_LABEL"

[ -z "$DEV_ENV" ] &&
	log --error "env var DEV_ENV needs to be present" &&
	exit 1

grepstr=""
dry_run="0"
mode="install"

while [[ $# -gt 0 ]]; do
	if [[ "$1" =~ ^--dry ]]; then
		dry_run="1"
	elif [[ "$1" == "uninstall" ]]; then
		mode="uninstall"
		yayflags=("-Rns")
	elif [[ ! "$1" == "install" ]]; then
		grepstr="$1"
	fi
	shift
done

export DEV_ENV="$DEV_ENV"
export LOG_ENABLE_DRY_RUN="$dry_run"
export RUN_GREP_STR="$grepstr"
export RUN_MODE="$mode"

log "RUN: -- grep: '$grepstr'"

find "$DEV_ENV/runs" \
	-mindepth 1 \
	-maxdepth 1 \
	-type f \
	-exec bash -xc "$DEV_ENV/runs/utils/run-handler {}" \;
