filename="/usr/local/bin/md-to-sh.sh"

conf_print_md_to_sh_sh() {
  cat <<-'EOF'
		#!/usr/bin/env bash
		# Convert Markdown → runnable Bash script

		if [ -z "$1" ]; then
			cat <<USAGE
			Usage: $(basename "$0") <file.md>
			USAGE
			exit 1
		fi

		INPUT_FILE="$1"
		OUTPUT_FILE="${INPUT_FILE%.md}.sh"

		cat <<HEADER > "$OUTPUT_FILE"
		#!/usr/bin/env bash
		# Auto-generated from ${INPUT_FILE} on $(date)

		HEADER

		IN_CODE_BLOCK=false
		FOUND_BLOCK=false

		while IFS= read -r line || [ -n "$line" ]; do
			if [[ "$line" =~ ^\`\`\` ]]; then
				IN_CODE_BLOCK=!$IN_CODE_BLOCK
				if [ "$IN_CODE_BLOCK" = true ]; then
					FOUND_BLOCK=true
				fi
				continue
			fi

			if [ "$IN_CODE_BLOCK" = true ]; then
				printf '%s\n' "$line" >> "$OUTPUT_FILE"
			else
				if [ -z "$line" ]; then
					printf '#\n' >> "$OUTPUT_FILE"
				else
					printf '# %s\n' "$line" >> "$OUTPUT_FILE"
				fi
			fi
		done < "$INPUT_FILE"

		if [ "$FOUND_BLOCK" = false ]; then
			cat <<ERR
			[ERROR] No code blocks found in $INPUT_FILE
			ERR
			exit 1
		fi

		chmod +x "$OUTPUT_FILE"

		cat <<MSG
		[SUCCESS] Generated: $OUTPUT_FILE
		MSG
	EOF
}

mkdir -p "$(dirname "${BUILD_DIR}${filename}")"
conf_print_md_to_sh_sh | tee "${BUILD_DIR}${filename}" >/dev/null
