#!/usr/bin/env bash
#
# Imitate watch from linux
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

############## Setup #########################

function cleanup {
    switch_to_main_screen
}
for sig in EXIT INT QUIT HUP TERM; do
  trap "set +e; cleanup; exit" "$sig"
done

############## Program #########################

function main {
    switch_to_alt_screen
    while true; do
        local output=$("$@")
        clear
        cat <<<"$output"
        sleep 2
    done
}

function switch_to_alt_screen {
    # tput smcup
    echo -e "\e[?1049h"
    clear
}

function switch_to_main_screen {
    # tput rmcup
    echo -e "\e[?1049l"
}

main "$@"