#!/usr/bin/env bash
set -e

has() {
	type "$1" >/dev/null 2>&1
}

# Root is no bueno
if [[ $EUID -eq 0 ]]; then
	echo "Theos should NOT be installed with or run as root (su/sudo)!" >&2
	echo "  - If you've installed Theos as root, please remove the install and" >&2
	echo "    reinstall as a non-root user." >&2
	echo "  - If you're using root because you don't have write permission for Theos'" >&2
	echo "    parent directory, please either install Theos to a different directory where" >&2
	echo "    you do have write permission, or if you're trying to install to /opt, change" >&2
	echo "    the directory's ownership using chown before attempting to install Theos as" >&2
	echo "    a non-root user." >&2
	exit 1
fi

# Ensure $THEOS is set and is a directory.
if [[ -z "$THEOS" || ! -d "$THEOS" ]]; then
	echo "\$THEOS must be set to the location of Theos to use $(basename $0)." >&2
	exit 2
fi

# Ensure $THEOS is a Git repo.
if [[ ! -d "$THEOS/.git" ]]; then
	echo "$THEOS is not a Git repository. Theos relies on Git to update itself. For more information, refer to: https://theos.dev/install#updating" >&2
	exit 3
fi

# Ensure the user has Git.
if ! has git; then
	echo "Git is not installed. Theos relies on Git to update itself. For more information, refer to: https://theos.dev/install" >&2
	exit 3
fi

cd "$THEOS"

# Set conflig flag so multiple git fetch jobs run simultaneously.
git config submodule.fetchJobs 4

# Update Theos itself, then submodules.
git pull --all --rebase=false
git submodule update --init --recursive

# The Theos update may need to do some extra stuff, so run the post-update script here.
exec bin/post-update
