#!/bin/sh
#
# TinyCM Command line tool. Dont use libtaz since TinyCM can run on any
# Linux/BSD distribution providing a web server with CGI SHell support
# such as LightTPD.
#
# Copyright (C) 2014-2017 SliTaz GNU/Linux - BSD License
#

list="tinycm.list"
path="${2%/}"
hgurl="http://hg.slitaz.org/tinycm"
dlurl="$hgurl/archive/tip.tar.bz2"

#
# Functions
#

boldify() {
	echo -e "\\033[1m$@\\033[0m"
}

error() {
	echo -e "\\033[1;31m$@\\033[0;39m"
}

usage() {
	cat << EOT

$(boldify "Usage:") $(basename $0) [command] [path|list]

$(boldify "Commands:")
  inst       Install TinyCM and set permissions
  up         Update one or a list of TinyCM installations

EOT
}

check_source() {
	if [ ! -f "Makefile" ] || [ ! -f "index.cgi" ]; then
		error "No source found" && exit 1
	fi
}

check_path() {
	if [ ! "$path" ]; then
		error "Missing path argument" && exit 1
	fi
}

check_tiny() {
	if [ ! -f "$path/index.cgi" ] || [ ! -d "$path/lib" ]; then
		error "Missing TinyCM in: $path"
		continue
	fi
}

#
# Commands
#

case "$1" in
	inst)
		check_source
		check_path
		echo ""
		boldify "Installing TinyCM..."
		echo "Path:"; echo "$path"
		mkdir -p $path
		for file in index.cgi style.css images lib plugins
		do
			echo "* Installing: $file"
			cp -a $file $path
		done
		if [ $(id) == 0 ]; then
			echo root
		else
			echo user
		fi
		echo "" ;;
	up)
		check_source
		if [ ! "$path" ] && [ ! -f "$list" ]; then
			error "Missing path argument or paths list: $list"
			exit 1
		fi
		echo ""
		boldify $(echo "Updating TinyCM installs...")
		
		# File liste of args
		if [ -f "$path" ]; then
			paths="$(cat ${list})"
		else
			paths="$path"
		fi
		
		for path in ${paths}
		do
			check_tiny
			echo "Updating: $path"
			cp -a index.cgi $path
			cp -a lib/functions.js $path/lib
			cp -a lib/jseditor.html $path/lib
			for plug in $(ls plugins)
			do
				if [ -d "$path/plugins/$plug" ]; then
					echo "* Updating plugin: $plug"
					cp -a plugins/$plug $path/plugins
				fi
			done
		done && echo "" ;;
	*)
		usage ;;
esac

exit 0
