#!/bin/bash

COURSE=$(hostname)
GITEASSH="ssh://git@focs.ji.sjtu.edu.cn:2222"

# when container starts network takes some time to come up
net_wait() {

	echo -n "Waiting for network"
	while ! wget -q --spider https://focs.ji.sjtu.edu.cn; do 
		echo -n .
		sleep 1
	done
	echo
}

# install config files from course-joj repo
import_config() {
 
	echo "Importing $COURSE JOJ configuration"

	cd /root
	git clone -b master $GITEASSH/$COURSE/$COURSE-joj.git 

	cd $COURSE-joj
	rsync -r etc/ /etc

	. /etc/joj-container-config.conf

}

services_restart() {

	echo "Restarting services"

	for i in $SERVICES; do 
		systemctl restart $i
	done

}

software_install() {

	echo "Installing $COURSE software"

    apt-get update && apt-get upgrade -y
    apt-get install -y $PACKAGES && apt-get clean

}

custom_commands() {
	for((i=0; i<${#COMMANDS[@]}; i++)); do
	  eval ${COMMANDS[i]};
    done
}

net_wait

import_config
software_install
services_restart
custom_commands

exit 0
