#!/usr/bin/env bash

set -euo pipefail

export PATH="/usr/bin:/bin:/usr/local/bin"
unset IFS
unset PYTHONPATH
unset PYTHONHOME
unset HTTP_PROXY
unset HTTPS_PROXY

main() {
    set -x
    local org_name
    local repo_name
    local course
    org_name=$(basename "$(dirname "$(pwd)")")
    repo_name=$(basename "$(pwd)")
    course=${repo_name%-*}
    if ! [[ "$course" =~ ^[a-zA-Z0-9_-]+$ ]]; then
        echo "FATAL: Invalid course name: $course" >&2
        exit 1
    fi

    local config_repo_path="/home/tt/.cache/$course-config"
    local grading_repo_path="/home/tt/.cache/$course-joj"
    local git_user="bot-$course"
    local git_email="bot-$course@focs.ji.sjtu.edu.cn"
    local git_server="ssh://git@focs.ji.sjtu.edu.cn:2222"
    local joj3_forge_exit_code=0

    # init repos if not exist
    if ! [ -d "$config_repo_path" ]; then
        git clone "$git_server/$course/$course-joj.git" "$config_repo_path"
        git -C "$config_repo_path" config user.name "$git_user"
        git -C "$config_repo_path" config user.email "$git_email"
    fi

    if ! [ -d "$grading_repo_path" ]; then
        git clone "$git_server/$course/$course-joj.git" "$grading_repo_path"
        git -C "$grading_repo_path" config user.name "$git_user"
        git -C "$grading_repo_path" config user.email "$git_email"
        git -C "$grading_repo_path" switch --orphan grading
        cat >"$grading_repo_path/Readme.md" <<EOF
# $course JOJ grading

This branch is automatically updated by JOJ, **never edit any file in this branch!**
EOF
        git -C "$grading_repo_path" add Readme.md
        git -C "$grading_repo_path" commit -m"docs: readme"
        git -C "$grading_repo_path" push -u origin grading
    fi

    # sync config repo
    git -C "$config_repo_path" reset --hard
    git -C "$config_repo_path" pull --rebase
    if [ -e "$config_repo_path/home/tt/.config/teapot/teapot.env" ]; then
        echo "FATAL: Forbidden file found in '/home/tt/.config/teapot/teapot.env'. Check the latest README to set TEAPOT_GITEA_TOKEN in secrets instead." >&2
        exit 1
    fi
    # optional .ssh path
    if [ -d "$config_repo_path/home/tt/.ssh/" ]; then
        rsync -a "$config_repo_path/home/tt/.ssh/" "/home/tt/.ssh"
    else
        echo "WARNING: No .ssh directory found in config repo"
    fi
    rsync -a --delete "$config_repo_path/home/tt/.config/" "/home/tt/.config"

    # check gitea token
    if [ -n "${TEAPOT_GITEA_TOKEN:-}" ]; then
        local teapot_config_dir="/home/tt/.config/teapot"
        mkdir -p "$teapot_config_dir"
        cat >"$teapot_config_dir/teapot.env" <<EOF
GITEA_ORG_NAME=$org_name
GITEA_ACCESS_TOKEN=$TEAPOT_GITEA_TOKEN
EOF
        if ! (cd /tmp && joint-teapot joj3-check-gitea-token "$teapot_config_dir/teapot.env"); then
            echo "FATAL: TEAPOT_GITEA_TOKEN invalid, ask admin to update it" >&2
            exit 1
        fi
    else
        echo "FATAL: TEAPOT_GITEA_TOKEN not set, ask admin to set it" >&2
        exit 1
    fi

    joj3-forge convert "/home/tt/.config/joj" || joj3_forge_exit_code=$?
    rsync -a --delete "/home/tt/.config/joj/" "$config_repo_path/home/tt/.config/joj"

    # enforce correct permissions
    chmod 751 "/home/tt/"
    chmod 750 "/home/tt/.cache/" || true
    chmod 750 "/home/tt/.cache/joj3" || true
    chmod 700 "/home/tt/.ssh/" || true
    chmod 700 "/home/tt/.config/"

    # commit config changes
    git -C "$config_repo_path" add home/tt/.config/joj
    if ! git -C "$config_repo_path" diff --staged --quiet; then
        commit_hash=$(git -C "$config_repo_path" rev-parse HEAD)
        git -C "$config_repo_path" commit -m "chore: $commit_hash trigger joj3-forge convert [skip ci]"
        git -C "$config_repo_path" push
    fi

    exit "$joj3_forge_exit_code"
}

main "$@"
