#!/bin/bash -e
# X-Con-Debian-Depends:

# Includes
CON_COMPAT="0.3.2" PATH="${PATH}:/usr/share/con-dev" . con-lib.bash
con::include opt conf vc bs dev dev-setup dev-meta dev-release

# Sanity check: don't ever run as root
[ "$(id -u)" != "0" ] || con::log:fatal "You are root. Please use con-dev as non-root user only."

CON_DEV_DEFAULT_PROJECT_CONF="./.con-dev/conf"
CON_DEV_DEFAULT_USER_CONFIG_DIR="${HOME}/.con-dev"
CON_DEV_FIND_PROJECTLIST_CMD="find '${CON_DEV_DEFAULT_USER_CONFIG_DIR}' -maxdepth 1 -mindepth 1 -name '*.conf' -exec basename '{}' '.conf' \; 2>/dev/null | tr '\n' ' '"

con_dev_setup()
{
	declare -i i=0
	local chars=("-" "\\" "|" "/")
	l()
	{
		printf "\r[%s] Setting up: %-80s\r" "${chars[${i}]}" "${1}..."
		i=$(((i+1)%${#chars[@]}))
	}

	# Auto-detect version control and build system
	l "build system"
	con::include @bs || true
	l "version control"
	con::include @vc || true

	# Set up config; defaults values may depend on previous bs/vc guesses
	l "configuration"
	con_dev_setup_setup

	con::term:set "clear_eol"
}

con_dev:cmd:status()
{
	if [[ -n "${CON_BS_PACKAGE}" ]]; then
		printf "$(con::term:printf "bold" "%%s") in $(con::term:printf "blue" "%%s"):\n\n" "${CON_BS_PACKAGE}" "$(pwd)"
		con_bs::status
		con_vc::status
	else
		printf "Projects known in $(con::term:printf "bold" "%%s"): %s\n" "$(con_opt::get D)" "$(con_dev_listProjects)"
	fi
}

con_opt::init "Software development tool for terminals."

con_opt::add -T "con_dev_type_project" -a "<project>" \
	"p" "Project to act on."
con_opt::add -d "master" -i "p" \
	"c" "Checkout mode: Work in a temporary fresh VC checkout (not wd)."

con_opt::add \
	"N" "No action mode: Just show what would be run (@todo CURRENTLY FOR 'release' ONLY!)"
con_opt::add -d "${CON_DEV_DEFAULT_PROJECT_CONF}" -a "<conffile>" -T "file" \
	"F" "Project config file location."
con_opt::add -d "${CON_DEV_DEFAULT_USER_CONFIG_DIR}" -a "<confdir>" -T "dir" \
	"D" "User config dir location."

# Commands
con_opt::cmd:add status "Get project status"
con_dev_setup_menu
con_dev_release_menu
con_libbs::opt_addLibCmds "bs"
con_libvc::opt_addLibCmds "vc"
con_dev_meta_menu

# Parse
con_opt::parse "${@}"

# @todo: Ponder on EDITOR and VISUAL; should always ask when non is found?
if [[ "${EDITOR}" = "" ]]; then
	if [[ "${VISUAL}" = "" ]]; then
		export EDITOR="vi"
	else
		export EDITOR="${VISUAL}"
	fi
fi
# Set VISUAL to EDITOR to force our preference for EDITOR
export VISUAL=${EDITOR}
con::log:debug "Using editor: ${EDITOR}"

# Change to project directory (if requested)
con_dev_enterProjectDir

con_dev_setup
con_opt::cmd:run
