#!/usr/bin/env bash

# Copyright (C) 2012, 2013, 2014 Johan Andersson
# Copyright (C) 2013-2014, 2016 Sebastian Wiesner

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with GNU Emacs; see the file COPYING.  If not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.

set -euo pipefail
CASK=$0
EMACS=${CASK_EMACS:-${EMACS:-emacs}}

if [ "$#" -eq "0" ] ; then
	subcommand=install
else
	subcommand=$1
	shift
fi

case $subcommand in
	emacs)
		EMACSLOADPATH="$($CASK load-path)" PATH="$($CASK path)" EMACS="$EMACS" "$EMACS" "$@"
		;;
	exec)
		EMACSLOADPATH="$($CASK load-path)" PATH="$($CASK path)" EMACS="$EMACS" "$@"
		;;
	*)
		WHICH=${WHICH:-which}
		READLINK=$($WHICH readlink || true)
		if [ "$(uname || true)" == "Darwin" ] ; then
			READLINK=
		fi
		READLINK=${READLINK:-$($WHICH greadlink || true)}
		if [ ! -z "$READLINK" ] ; then
			SRCDIR__=$($READLINK -f "$CASK")
		else
			SRCDIR__=$(python -c "import os, sys; print(os.path.realpath(sys.argv[1]))" "$CASK")
		fi
		SRCDIR_=$(dirname "$SRCDIR__")
		SRCDIR=$(dirname "$SRCDIR_")
		"$EMACS" -Q --script "$SRCDIR/cask-cli.el" -- $subcommand "$@"
		;;
esac
