#!/bin/bash
ask_yn () {
    echo "$@"
    while read -r; do
        case $REPLY in
            [Yy]*) return 0;;
            [Nn]*) return 1;;
            *) echo "Enter yes or no";;
        esac
    done
    return 2
}

wehave () {
    command -v "$1" &>/dev/null
}

fn=./_ts
new=false
yes=false
OPTIND=1
while getopts :nyfh opt; do
    case $opt in
        n|f) new=true ;;
        y) yes=true ;;
        h)
            echo "Usage: $0 [-nfy] [filetype] [filename]"
            echo "-n or -f will erase an existing testscript"
            echo "-y will run without confirmation"
            exit 0
            ;;
        *) : ;;
    esac
done
shift $(( OPTIND - 1 ))

if [[ $# -lt 1 ]]; then
    if [[ $SHELL = *csh ]]; then
        cmd=$SHELL
    else
        cmd="${SHELL:-/bin/bash} -il"
    fi
else
    case $1 in
        py) cmd=python ;;
        py2) cmd=python2 ;;
        py3) cmd=python3 ;;
        pl) cmd=perl ;;
        rb) cmd=ruby ;;
        tcl) cmd=tclsh ;;
        *)  cmd=$1
            ;;
    esac
    if ! cmd=$(command -v "$cmd"); then
        echo "Couldn't find $1"
        exit 127
    fi
    shift
fi
if [[ $1 ]]; then
    if [[ $1 = /* ]]; then
        fn=$1
    else
        fn=./$1
    fi
fi
if $new; then
    rm -f "$fn"
fi
if [[ ! -e $fn ]]; then
    echo "#!$cmd" > "$fn"
    echo >> "$fn"
fi

editor=${VISUAL:-${EDITOR:-}}
if [[ -z $editor ]]; then
    if wehave editor; then
        editor=editor
    elif wehave vim; then
        editor=vim
    elif wehave emacs; then
        editor="emacs -nw"
    elif wehave jstar; then
        editor=jstar
    elif wehave joe; then
        editor=joe
    elif wehave vi; then
        editor=vi
    elif wehave nano; then
        editor=nano
    else
        echo >&2 No editor found
        exit 127
    fi
fi
set -e
$editor "$fn"
chmod +x "$fn"
if $yes || ask_yn "Run $fn? (y/n)"; then
    PATH="$PATH:$(pwd)" \
        PYTHONPATH="${PYTHONPATH+$PYTHONPATH:}$(pwd)" \
        PERL5LIB="${PERL5LIB+$PERL5LIB:}$(pwd)" \
        RUBYLIB="${RUBYLIB+$RUBYLIB:}$(pwd)" \
        exec "$fn"
    echo >&2 Exec failed
    exit 255
fi
