#!/bin/sh -
APPENV="${APPENV-/app/env}"; export APPENV
PATH="$APPENV/bin:$PATH:/bin:/usr/bin:/usr/local/bin"; export PATH
fqdn="${ITERMOCILX_FQDN-`which fqdn`}"; test -z "$fqdn" && fqdn=echo

dfltdir="${ITERMOCILX_CFG:-$HOME/.itermocil}"
ssh="${ITERMOCILX_SSH-ssh}"

pub=https://appenv.med.umich.edu/log/remotecfg/itermocil.tgz

# itermocil-layout - create itermocil layout files from the given input
# Steve Kinzler, steve@kinzler.com, Sep 22
# https://kinzler.com/me/home.html#macos

see=https://github.com/TomAnthony/itermocil

case "$1" in
-h)	echo <<EOF 1>&2
usage: $0 [ dir [ file ... ] ]"
Input format: #ITERMOCIL# name layout host ...
EOF
	exit 1;;
esac

case "$#" in
0)	dir="$dfltdir";;
*)	dir="$1"; shift;;
esac
mkdir -p "$dir" || exit 2

cat "$@" | perl -ne 'next unless s/^\s*#ITERMOCIL#\s*//; chomp;
	$argv .= " $_", next if s/\s*\\\s*$//;
	$argv .= " $_"; @_ = split(/\s+/, $argv); shift @_; $argv = "";
	$name = $file = shift @_; $file =~ s,/,_,g; $lay = shift @_;
	warn("$!\n"), next unless open(YML, ">'"$dir"'/$file.yml");
	print YML "windows:\n  - name: $name\n    root: ~\n",
		  "    layout: $lay\n    panes:\n";
	foreach (@_) { $_ = `"'"$fqdn"'" $_`; chomp;
		       print YML "      - ",
				 /^-$/ ? "hostname" : "'"$ssh"' $_", "\n" }'

cat > "$dir"/README <<EOF
See $see
Install the files herein to ~/.itermocil
EOF

cat > "$dir"/Makefile <<EOF
URL = $pub

update:
	curl -Lks \$(URL) | tar xzvf -
EOF
