#!/bin/bash
set -e

# /home/git/repo/{$2 :: <{repo_name}>/stone/xx/xx/xxhashxx}
file_path=$(realpath -m "/home/git/repo/$2")
repo_path=$(realpath -m "$(dirname $file_path)/../../..")

if [[ $repo_path != /home/git/repo/* ]]; then
	exit 1
fi

if [[ $file_path != ${repo_path}/stone/* ]]; then
	exit 1
fi

if [ "$1" == "-f" ]; then
	if [[ ! -f $file_path ]]; then
		exit 1
	fi
	scp -f $file_path
elif [ "$1" == "-t" ]; then
	c=$(cat ${repo_path}/c)
	p=$(cat ${repo_path}/p)
	for can in $p $c; do
		if [ "$can" == "$GIT_USER" ];then
			pass=1
			break
		fi
	done
	[ $pass -eq 1 ]
	if [[ -d $file_path ]]; then
		exit 1
	fi
	if [[ -f $file_path ]]; then
		exit 0
	fi
	mkdir -p $(dirname $file_path)
	scp -t $file_path
else
	exit 1
fi
