#!/usr/bin/env sh
# Quickly create and edit a new shell script, already marked as executable
#
# Usage:
#
#   new-sh foo.sh
#   new-sh foo.py python

while getopts h opt; do
    case $opt in
    h) awk 'NR == 1 { next } /^$/ { exit } { print substr($0, 3) }' "$0"
       exit ;;
    esac
done
shift $(( OPTIND - 1 ))

script="${1:?Script name required.}"
lang=${2:-sh}

if [ -e "$script" ]; then
    printf 'Script "%s" already exists.\n' "$script" 1>&2
    exit 1
fi

printf "#!/usr/bin/env $lang\n" > "$script"
chmod +x "$script"

case "$lang" in
    sh)
        case "$script" in
        'start.sh') cat >> "$script" <<-'EOS'

INITIAL_PANE="$(tmux display -p '#{pane_id}')"
INITIAL_PATH="$(tmux display -p '#{pane_current_path}')"

tmux renamew 'Foo'

tmux splitw -l 3 -c "${INITIAL_PATH}/path/to/client"
tmux send 'npm start' Enter
tmux selectp -T 'http://localhost:8080'

tmux splitw -h -c "${INITIAL_PATH}/path/to/server"
tmux send 'python -m http.server' Enter
tmux selectp -T 'http://localhost:8000'

tmux selectp -t "$INITIAL_PANE"

cat <<'EOF'
             ____________________
            /                    \
            |   Foo server is    |
            |      running.      |
            \____________________/
                     !  !
                     !  !
                     !  !
                     !  !
                     !  !
          * .,   *. *! *! ,., . *
 _________)^\\_//(\/(/\)/\/`\^`_)_______

EOF
EOS
;;

        *) cat >> "$script" <<-'EOS'
# Short Description
#
# `NAME [<flags>] (command [<arg>, <name=value>...])`
#
#     NAME -h              # Short, usage help text.
#
# Flag | Description
# ---- | -----------
# -h   | Show this screen.
# -x   | Enable xtrace debug logging.

NAME=$(basename "$0")
TEMP="${TMPDIR-/tmp}/${NAME}.${$}.$(awk \
    'BEGIN {srand(); printf "%d\n", rand() * 10^10}')"

local opt
local OPTARG
local OPTIND

while getopts hx opt; do
    case $opt in
    h) awk 'NR == 1 {next} /^$/ {exit} {print substr($0, 3)}' "$0"; exit;;
    x) set -x;;
    esac
done
shift $(( OPTIND - 1 ))

trap '
    excode=$?; trap - EXIT;
    rm -rf -- '"$TEMP"'
    exit $excode
' INT TERM EXIT

mkdir -m 700 "$TEMP"
if [ $? -ne 0 ]; then
    printf 'Error creating temp directory.\n' 1>&2
    exit 1
fi

printf 'Hello, world.\n'
EOS
;;

        esac;;
esac

${EDITOR:-vi} -c ':1' "$script"
