#!/bin/zsh               
use scwrypts/environment-files
#####################################################################

MAIN() {
	[ $1 ] && ENV_NAME="$1"
	
	[ ! $1 ] && {
		[ $SCWRYPTS_ENV ] \
			&& ENV_NAME=$SCWRYPTS_ENV \
			|| ENV_NAME=$(SCWRYPTS__SELECT_OR_CREATE_ENV)
	}
	[ ! $ENV_NAME ] && ABORT
	
	ENV_FILES=($(SCWRYPTS__GET_ENV_FILES $ENV_NAME 2>/dev/null))
	for ENV_FILE in ${ENV_FILES[@]}
	do
		[ ! -f "$ENV_FILE" ] && {
			STATUS "Creating '$ENV_FILE'..." \
				&& mkdir -p "$(dirname "$ENV_FILE")" \
				&& touch "$ENV_FILE" \
				&& ((CREATED+=1)) \
				&& SUCCESS "created '$ENV_NAME'" \
				|| { ERROR "failed to create '$ENV_FILE'"; exit 1; }
		}
	
		[ $CREATED ] && [[ $CREATED -gt 0 ]] && {
			STATUS "detected new environment files; performing sync" \
				&& SCWRYPTS__RUN --name scwrypts/environment/synchronize --group scwrypts --type zsh -- --no-prompt \
				|| FAIL 1 "failure during sync for '$ENV_NAME'" \
		}
			;
	done
	
	EDIT $ENV_FILES
	
	SCWRYPTS__RUN --name scwrypts/environment/synchronize --group scwrypts --type zsh -- --no-prompt \
		|| FAIL 4 'failed to run environment sync' \
		;
	
	SUCCESS "environment '$ENV_NAME' successfully modified"
}
