#!/bin/bash

# exit on error
echoerr() { ERR=$1; shift; echo -e "Error: $@" 1>&2; exit $ERR; }

# exit if no course provided
[ -z $1 ] && echoerr 255 "Usage: $0 coursecode"

COURSE=$1
COURSECFG=$HOME/courses/$COURSE
GITEAAPI="https://focs.ji.sjtu.edu.cn/git/api/v1"


read -n 1 -p "Before proceeding confirm that $COURSE organization, $COURSE-joj repository, and bot-$COURSE user exist: [y/N] " READY
[ "x$READY" = "xy" ] || { echo; exit; }


# dir for course config/setup
[ -d $COURSECFG ] || mkdir $COURSECFG


fs_create() {

	echo "Creating FS"

	sudo zfs create -o mountpoint=/home/ja/.local/share/lxc/$COURSE joj/$COURSE
	sudo chown 100000:ja $HOME/.local/share/lxc/$COURSE
	sudo chmod g+w $HOME/.local/share/lxc/$COURSE

}

# generate token (write user: ssh key, read org: action runner token)
# create course-joj action secret for teapot
gitea_config() {
	if [ ! -e $COURSECFG/teapot.env ]; then
		echo "Configuring Gitea access"
		
		read -s -p "Input bot-$COURSE passwd: " BOTPWD
		GTOKEN=$(curl -s -X POST -u "bot-$COURSE:$BOTPWD" "$GITEAAPI/users/bot-$COURSE/tokens" -H "Content-Type: application/json"  -d '{"name":"teapot","scopes":["write:issue", "read:organization", "write:repository", "write:user"]}' | jq -r '.sha1')
		echo -e "GITEA_ORG_NAME=$COURSE\nGITEA_ACCESS_TOKEN=$GTOKEN" > $COURSECFG/teapot.env

		. $COURSECFG/teapot.env

		curl -s -X PUT "$GITEAAPI/repos/$COURSE/$COURSE-joj/actions/secrets/TEAPOT_GITEA_TOKEN" -H "Content-Type: application/json"  -d "{\"data\":\"$GITEA_ACCESS_TOKEN\"}" -H "Authorization: Bearer $GITEA_ACCESS_TOKEN"

	else
		. $COURSECFG/teapot.env
	fi


}

ssh_config() {

	[ -d $COURSECFG/ssh ] || mkdir $COURSECFG/ssh

	if [ ! -e "$COURSECFG/ssh/id_ed25519" ]; then
		echo "Generating SSH key"
		ssh-keygen -t ed25519 -N "" -f $COURSECFG/ssh/id_ed25519

		PUBKEY=$(cat $COURSECFG/ssh/id_ed25519.pub)
		curl -s -X POST "$GITEAAPI/user/keys" -H "Authorization: Bearer $GITEA_ACCESS_TOKEN" -H "Content-Type: application/json"  -d "{\"key\":\"$PUBKEY\", \"title\":\"tt@$COURSE\"}"
	fi

}

ar_preconfig() {
	if [ ! -e $COURSECFG/act_runner.token ]; then
		echo "Getting an act_runner token"
		curl -X GET -s "$GITEAAPI/orgs/$COURSE/actions/runners/registration-token?token=$GITEA_ACCESS_TOKEN" | jq -r '.token' > $COURSECFG/act_runner.token
	fi
}


container_create() {
	
	echo "Creating container $COURSE"

	lxc-stop jtc 2>/dev/null

#	lxc-copy -n jtc -N $COURSE --logfile $COURSE.log --logpriority DEBUG
	lxc-copy -n jtc -N $COURSE
	
}

container_config() {
	lxc-start -n $COURSE
	lxc-attach -n $COURSE --clear-env -v HOME=/root -v TERM=tmux /usr/local/bin/joj-container-config
}


#
# deploy
#

fs_create

gitea_config
ssh_config
ar_preconfig

container_create
container_config

echo done

