#!/usr/bin/bash
# Copyright (c) 2015-2019 Eric Vidal <eric@obarun.org>
# All rights reserved.
# 
# This file is part of Obarun. It is subject to the license terms in
# the LICENSE file found in the top-level directory of this
# distribution.
# This file may not be copied, modified, propagated, or distributed
# except according to the terms contained in the LICENSE file.

PROG="66-mods.sh"
service_system="${service_system:-/usr/lib/66/service}"
module_system="${module_system:-/usr/lib/66/module}"
force=0

out() {
	msg="${1}"
	66-echo -- $PROG: $msg 
}

die() {
	out "${1}"
	exit 111
}

usage () {
cat <<EOF
$PROG [ -h ] [ -H ] [ -f ] module@instance

$PROG <options> modules@instance

options :
    -h: print this help
    -H: print module help
    -f: force to overwrite an existing module
EOF
exit 0
}

for arg ; do
  case "$arg" in
    -h|--help) usage ;;
    -H|--help-module) hm=1 ;;
    -f|--force) force=1 ;;
    -*) die "fatal: unknown option $arg" ;;
    *) target+=( $arg ) ;;
  esac
done

if [[ "${target[0]}" != *"@"* ]];then
	die "fatal: invalid argument -- not a module name"
fi

mod="${target[0]}"
mod="${mod%%@*}"
mod="${mod%%@*}@"
insta="${target[0]}"
insta="${insta##*@}"

if [[ ! -d ${module_system}/${mod} ]]; then
	die "fatal: module ${mod} doesn't exist"
fi

if (( ${hm} )); then
	if [[ -e ${module_system}/${mod}/.configure/help ]]; then
		h=$(<${module_system}/${mod}/.configure/help)
		66-echo -- "${h}"
	else
		out "warning: no help found for ${mod}"
	fi
	exit 0
fi

if [[ -z "${insta}" ]];then
	die "fatal: instance for ${mod} is not set" 
fi

if [[ -d ${service_system}/${mod} ]]; then
	if (( !$force )) ; then
		die "fatal: ${service_system}/${mod} already exist"
	else
		rm -rf ${service_system}/${mod} || die "fatal: unable to remove ${service_system}/${mod}"
	fi
fi

cp -rT ${module_system}/${mod} ${service_system}/${mod} || die "fatal: unable to cp ${module_system}/${mod} to ${service_system}/${mod}"

## @I in file 
for i in $(find ${service_system}/${mod} -mindepth 1 -type f);do
	sed -i "s:@I:${insta}:g" $i || die "fatal: unable to sed ${i}"
done

## change directory name
for i in $(find ${service_system}/${mod} -mindepth 1 -type d|grep -v "configure");do
	mv $i $(66-echo -- ${i}|sed "s:@M:${insta}:g") || die "fatal: unable to move ${i} to $(echo ${i}|sed "s:@M:${insta}:g")"
done

## change file name
for i in $(find ${service_system}/${mod} -mindepth 1 -type f|grep -v "configure");do
	mv $i $(66-echo -- ${i}|sed "s:@M:${insta}:g") || die "fatal: unable to move ${i} to $(echo ${i}|sed "s:@M:${insta}:g")"
done

## run .configure scripts
if [[ -x ${service_system}/${mod}/.configure/configure ]]; then
	cd ${service_system}/${mod}/.configure/
	${service_system}/${mod}/.configure/configure ${insta} || die "fatal: unable to configure ${service_system}/${mod}"
	rm -rf ${service_system}/${mod}/.configure || die "fatal: unable to remove ${service_system}/${mod}/.configure"
fi
