#!/bin/bash

COURSE=$(hostname)
SEMESTER=${COURSE#*-}
COURSE=${COURSE%-*}

#
# initial repo/config setup
#
init() {

        [ -d $COURSE-config ] && backup $COURSE-config

        git clone ssh://git@focs.ji.sjtu.edu.cn:2222/$COURSE-$SEMESTER/$COURSE-joj.git $COURSE-config

        cd $COURSE-config

# copy config files
        rsync -r ./$HOME/ $HOME

# check existence of grading branch
        git branch -a | grep -q grading && br=1

        cd ..

# backup current grading scoreboard
        [ -d $COURSE-joj ] && backup $COURSE-joj

# clone grading branch or create one + push readme
        if [ "x$br" = "x1" ]; then
                git clone -b grading ssh://git@focs.ji.sjtu.edu.cn:2222/$COURSE-$SEMESTER/$COURSE-joj.git
                cd $COURSE-joj
                git switch grading
                git pull
        else
                git clone ssh://git@focs.ji.sjtu.edu.cn:2222/$COURSE-$SEMESTER/$COURSE-joj.git

                cd $COURSE-joj
                git switch --orphan grading

                echo "# $COURSE JOJ grading" > Readme.md
                echo "This branch is automatically updated by JOJ, **never edit any file in this branch!**" >> Readme.md

                git add Readme.md
                git commit -m"docs: readme"
                git push
        fi

}

#
# update config repo + copy config files
#
update() {

        [ -d "$COURSE-joj" ] || ( echo "ERROR: init first!" 1>&2 && exit )
        cd $HOME/.cache/$COURSE-config

        git pull

        rsync -r ./$HOME/ $HOME

}

#
# simple local backup
#
backup() {

        BCK="$HOME/.local/share/joj/$1-$(date +%y%m%d-%H%M%S)"
        echo "WARNING: $1 already exits, backing it up to $BCK"
        mv "$1" "$BCK"

}

[ -z "$1" ] && echo "Usage: $0 update|init"

cd $HOME/.cache
$1
