#!/usr/bin/env bash
set -euo pipefail

# 从 git 拉取/更新仓库，然后调用仓库内 scripts/deploy-ubuntu.sh。

REPO="${REPO:-git@git.n.xiaomi.com:wuyang6/zk-data-agent.git}"
BRANCH="${BRANCH:-main}"
APP_DIR="${APP_DIR:-${HOME}/zk-data-agent}"
FORCE=0
BOOTSTRAP_SYSTEM="${BOOTSTRAP_SYSTEM:-0}"

usage() {
	cat <<EOF
Usage: bash install-from-git.sh [--repo REPO] [--branch BRANCH] [--dir APP_DIR] [--force] [--bootstrap-system]
EOF
}

while [[ $# -gt 0 ]]; do
	case "$1" in
		--repo)
			REPO="$2"
			shift 2
			;;
		--branch)
			BRANCH="$2"
			shift 2
			;;
		--dir)
			APP_DIR="$2"
			shift 2
			;;
		--force)
			FORCE=1
			shift
			;;
		--bootstrap-system)
			BOOTSTRAP_SYSTEM=1
			shift
			;;
		-h|--help)
			usage
			exit 0
			;;
		*)
			echo "Unexpected argument: $1" >&2
			usage >&2
			exit 1
			;;
	esac
done

command -v git >/dev/null 2>&1 || {
	echo "Missing git. Please install git first." >&2
	exit 1
}

if [[ -e "${APP_DIR}" && ! -d "${APP_DIR}/.git" ]]; then
	echo "${APP_DIR} already exists but is not a git repository." >&2
	echo "Please move it away, or rerun with --force to replace it." >&2
	if [[ "${FORCE}" != "1" ]]; then
		exit 1
	fi
	rm -rf "${APP_DIR}"
fi

if [[ -d "${APP_DIR}/.git" ]]; then
	cd "${APP_DIR}"
	git fetch origin
	git checkout "${BRANCH}"
	if [[ "${FORCE}" == "1" ]]; then
		git reset --hard "origin/${BRANCH}"
	else
		git pull --ff-only origin "${BRANCH}"
	fi
else
	git clone --branch "${BRANCH}" "${REPO}" "${APP_DIR}"
	cd "${APP_DIR}"
fi

deploy_args=("${BRANCH}" "--skip-git")
if [[ "${BOOTSTRAP_SYSTEM}" == "1" ]]; then
	deploy_args+=("--bootstrap-system")
fi
bash scripts/deploy-ubuntu.sh "${deploy_args[@]}"
