#!/usr/bin/env bash

# Simple output
echo "This is how you print things out followed by a newline."
printf "%s" "This is how you print "
printf "%s" "things without a newline."
echo
printf "\n%s\n" "This is how you print things surrounded by newlines."

# Colors
FG_BLACK=$(tput setaf 0)
FG_RED=$(tput setaf 1)
FG_GREEN=$(tput setaf 2)
FG_YELLOW=$(tput setaf 3)
FG_BLUE=$(tput setaf 4)
FG_MAGENTA=$(tput setaf 5)
FG_CYAN=$(tput setaf 6)
FG_WHITE=$(tput setaf 7)
BG_BLUE=$(tput setab 4)
RESET=$(tput sgr0)

# Colorful text
echo "${FG_RED}Colorful text ${FG_GREEN}is just ${FG_YELLOW}for funsies.${RESET}"
echo "${FG_BLUE}Its usually ${FG_MAGENTA}more trouble ${FG_CYAN}than it's ${BG_BLUE}worth.${RESET}"

SEP="########################################################################"

printf "\n${FG_RED}%s${RESET}\n" "$SEP"

# Print grid of colors
for COLORID in {0..255} ; do
    printf "$(tput setaf "$COLORID")%s${RESET} " "${COLORID}"
    if [[ "$COLORID" -gt 0 ]] && [ $(($COLORID % 15)) -eq 0 ]; then
        echo;
    fi
done

printf "\n${FG_GREEN}%s${RESET}\n" "$SEP"

# redirect stdout
mkdir cache
echo "hello" > cache/written.txt
echo "written.txt contents:"
printf "%s" "$FG_GREEN" && cat cache/written.txt && printf "%s" "$RESET"

printf "\n${FG_YELLOW}%s${RESET}\n" "$SEP"

# overwrite an existing file
echo "goodbye" > cache/written.txt
echo "written.txt contents:"
printf "%s" "$FG_YELLOW" && cat cache/written.txt && printf "%s" "$RESET"

printf "\n${FG_BLUE}%s${RESET}\n" "$SEP"

# append to a file
echo "okay" >> cache/written.txt
echo "written.txt contents:"
printf "%s" "$FG_BLUE" && cat cache/written.txt && printf "%s" "$RESET"

printf "\n${FG_MAGENTA}%s${RESET}\n" "$SEP"

# Redirect stderr
echo "//" | sed "s/$PATH//g" 2> cache/stderr.txt 1> cache/stdout.txt
echo "stdout.txt contents:"
printf "%s" "$FG_MAGENTA" && cat cache/stdout.txt && printf "%s" "$RESET"
echo "stderr.txt contents:"
printf "%s" "$FG_MAGENTA" && cat cache/stderr.txt && printf "%s" "$RESET"

printf "\n${FG_CYAN}%s${RESET}\n" "$SEP"

# Redirect stderr to stdout and stdout to a file
wget http://localhost:8080/index.html &> cache/stderr-and-stdout.txt
echo "stderr-and-stdout.txt contents:"
printf "%s" "$FG_CYAN" && cat  cache/stderr-and-stdout.txt && printf "%s" "$RESET"

printf "\n${FG_WHITE}%s${RESET}\n" "$SEP"

# Split output into a file and into stdout using tee
echo "example string" | tee cache/tee.txt | sed "s/example/prod/g"
echo "tee.txt contents:"
printf "%s" "$FG_WHITE" && cat cache/tee.txt && printf "%s" "$RESET"

printf "\n${FG_BLACK}%s${RESET}\n" "$SEP"

rm -rf cache
