#!/bin/sh

########## VARIABLES
VERSION="@VERSION@"
DATADIR="@DATADIR@"

########## GENERIC FUNCTIONS

pinfo()  { printf %s\\n "${__green}${__bold}LOG${__reset}: $*"; }
pwarn()  { printf %s\\n "${__yellow}${__bold}WARN${__reset}: $*" >&2; }
perror() {
    __error=${1:-1}
    shift
    printf %s\\n "${__red}${__bold}ERROR${__reset}: $*" >&2
    exit "$__error"
}
pdie() {
    perror 1 "$*"
}

HELP='[PICO_WAYFIRE_TARGETS="targets"] pico-wayfire [help]'
usage() {
    pdie "usage: ${HELP}"
}

if [ -n "${TERM}" ] && [ "${TERM}" != "dumb" ]; then
    export __bold="$(tput bold)" \
    __red="$(tput setaf 1)" \
    __green="$(tput setaf 2)" \
    __yellow="$(tput setaf 3)" \
    __reset="$(tput sgr0)"
fi

########## PICO WAYFIRE

if [ $# -eq 1 ] && [ "${1}" = "help" ]; then
    if [ ! -d "${DATADIR}" ]; then
	pdie "Dirty installation - '${DATADIR}' does not exist"
    fi
    pinfo "Pico Wayfire v${VERSION}"
    pinfo "Available targets are:"
    for __target in "${DATADIR}"/*; do
	if [ -d "${__target}" ]; then
	    pinfo " - ${__target##*/}"
	fi
    done
    unset __target
    exit
elif [ $# -eq 1 ] && [ "${1}" != "help" ] ; then
    usage
elif [ $# -gt 1 ]; then
    usage
fi

if [ -z ${HOME+unset} ] || [ ! -d "${HOME}" ] ; then
    pdie "HOME is invalid"
fi

__install_target() {
    if [ $# -ne 1 ]; then
	pdie "need an install target"
    fi
    if [ ! -d "${1}" ]; then
	pdie "install target '${1}' does not exist"
    fi
    pinfo "installing - ${1}..."
    if [ -e "${1}/pre_install" ] && [ -f "${1}/pre_install" ]; then
	. "${1}/pre_install"
    fi
    if [ -d "${1}/data" ]; then
	cp -a "${1}/data/". "${HOME}"
    fi
    if [ -e "${1}/post_install" ] && [ -f "${1}/post_install" ]; then
	. "${1}/post_install"
    fi
    pinfo "finished - ${1}"
}

if [ -z ${PICO_WAYFIRE_TARGETS+unset} ]; then
    for __target in "${DATADIR}"/*; do
	if [ -d "${__target}" ]; then
	    __install_target "${__target}"
	fi
    done
else
    for __target in ${PICO_WAYFIRE_TARGETS}; do
	if [ -d "${DATADIR}/${__target}" ]; then
	    __install_target "${DATADIR}/${__target}"
	fi
    done
fi
unset __target

########## FINISHED ##########
pinfo "Finished setting up Pico Wayfire v${VERSION}"
