#!/bin/sh
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(dirname "$SCRIPT_DIR")"
SING_BOX="$ROOT/works/sing-box"
REV_FILE="$ROOT/works/rev"

# defaults
REPO_URL="git@git.inker.bot:arknights/sing-box.git"
if [ ! -z "$CI_JOB_TOKEN" ]; then
  git config --global user.name imabot
  git config --global user.email ci@inker.bot
  git config --global url."https://gitlab-ci-token:${CI_JOB_TOKEN}@git.inker.bot/".insteadOf "git@git.inker.bot:"
fi
UPSTREAM_BRANCH="main"

CONFIG="$ROOT/works/config"
if [ -f "$CONFIG" ]; then
    . "$CONFIG"
fi

if [ -d "$SING_BOX/.git" ]; then
    echo "Updating sing-box..."
    git -C "$SING_BOX" fetch --all
    if [ -n "$UPSTREAM_BRANCH" ]; then
        git -C "$SING_BOX" checkout "$UPSTREAM_BRANCH"
    fi
    git -C "$SING_BOX" pull
else
    echo "Cloning sing-box..."
    if [ -n "$UPSTREAM_BRANCH" ]; then
        git clone -b "$UPSTREAM_BRANCH" "$REPO_URL" "$SING_BOX"
    else
        git clone "$REPO_URL" "$SING_BOX"
    fi
fi

REV="$(git -C "$SING_BOX" rev-parse HEAD)"
echo "$REV" > "$REV_FILE"

echo "Done. Version: $(git -C "$SING_BOX" describe --tags --always 2>/dev/null || echo "$REV")"
echo "Stored rev: $REV"
