#!/bin/sh
# create or clone GIT repository into sandbox
# Copyright (C) 2018 FARGOS Development, LLC
# $Id$
# Depends upon getsbattr, sbrel
originDir=`dirname $0`
thisDir=`pwd`

# get sandbox-specific settings
sb_gitServer=`${originDir}/getsbattr -null gitServer`
sb_gitRoot=`${originDir}/getsbattr -null gitRoot`

# If sandbox-specific not defined, fill in from environment
# Should be something like ssh://gitUser@server:
gitServer=${sb_gitServer:-${GIT_HOST}}
# Should be something like path/to/repositories
gitRoot=${sb_gitRoot:-${GIT_PATH}}
# subqualifier if not already embedded in GIT_PATH
gitRepository=""

doCreateOnServer=0 # do push to create repository on server
useSubModules=0

relDir=`${originDir}/sbrel`
relRoot=`${originDir}/sbrel -showroot`
dirList=""
flags=""
forceFlag=""
revisionFlags=""
checkoutCmd="co --depth empty"
checkoutDir="co"
updateCmd="update"

while test $# -gt 0
do
	case "${1}" in
	-h | -help | --help)
		printf "usage: %s [--create] [--server modeAndhostName] [--path pathToRepository] [--respository name] [--force] dirOrFileName ...\n" "${0}" >&2
		exit 1
		;;
	--create | -create)
		doCreateOnServer=1
		;;
	--submodules)
		useSubModules=1
		;;
	--blame)
		checkoutCmd="blame"
		checkoutDir="blame"
		updateCmd="blame"
		;;
	-server | --server)
		gitServer="${2}"
		shift
		;;
	-path | --path)
		gitRoot="${2}"
		shift
		;;
	--repository)
		gitRepository="${2}"
		;;
	-r | --revision | --depth | --username | --password | --config-dir | --config-option) # two-element argument
		flags="${flags}${flags:+ }${1} ${2}"
		shift
		;;
	-force | --force)
		forceFlag="--force"
		;;
	-*) # single-element flag
		flags="${flags}${flags:+ }${1}"
		;;
	*)
		dirList="${dirList}${dirList:+ }${1}"
		;;
	esac
	shift
done

if test -z "${dirList}"
then
	printf "%s: no directories specified\n" "${0}" >&2
	exit 1
fi

set -x
if test ! -e "${STS}/.git"
then # initialize as git repository
	(cd "${STS}"; git init; git remote add origin "${gitServer}${gitRoot}${gitRepository:+/}${gitRepository}" )
	if test ${doCreateOnServer} -eq 1
	then # populate server with initial image
		if test ! -e "${STS}/.gitattributes"
		then # create a default .gitattributes file
			cat >> "${STS}/.gitattributes" <<endAttrLines
# default GIT atttributes
'*' text eol=lf
'*' ident
'*.awk' text

endAttrLines
			(cd "${STS}"; git add .gitattributes)
		fi
		# push changes
		(cd "${STS}"; git push origin master)
	fi
fi

if test -e "${STS}/.gitmodules"
then
	useSubModules=1
fi

(cd "${STS}"; git fetch --depth 1 "${gitServer}${gitRoot}${gitRepository:+/}${gitRepository}" )

for entryDir in ${dirList}
do
	# Always start from original context
	fullPath="${relDir}/${entryDir}"
	parentPath=`dirname ${fullPath}`
	parentDir=`dirname ${relRoot}${fullPath}`	# is absolute path
	entry=`basename ${fullPath}`			# should be last component of entryDir

	if test ${useSubModules} -eq 1
	then
		git submodule add ${gitHost}${gitRoot}/${entry}
	fi
done
