#!/bin/sh
# XXX: This should be removed when elixir's releases get custom command support

detect_flavour() {
	arch="$(uname -m)"
	if [ "$arch" = "x86_64" ]; then
		arch="amd64"
	elif [ "$arch" = "armv7l" ]; then
		arch="arm"
	elif [ "$arch" = "aarch64" ]; then
		arch="arm64"
	else
		echo "Unsupported arch: $arch" >&2
		exit 1
	fi

	if getconf GNU_LIBC_VERSION >/dev/null; then
		libc_postfix=""
	elif [ "$(ldd 2>&1 | head -c 9)" = "musl libc" ]; then
		libc_postfix="-musl"
	elif [ "$(find /lib/libc.musl* | wc -l)" ]; then
		libc_postfix="-musl"
	else
		echo "Unsupported libc" >&2
		exit 1
	fi

	echo "$arch$libc_postfix"
}

detect_branch() {
	version="$(cut -d' ' -f2 <"$RELEASE_ROOT"/releases/start_erl.data)"
	# Expected format: major.minor.patch_version(-number_of_commits_ahead_of_tag-gcommit_hash).branch
	branch="$(echo "$version" | cut -d'.' -f 4)"
	if [ "$branch" = "develop" ]; then
		echo "develop"
	elif [ "$branch" = "" ]; then
		echo "stable"
	else
		# Note: branch name in version is of SemVer format and may only contain [0-9a-zA-Z-] symbols —
		#   if supporting releases for more branches, need to ensure they contain only these symbols.
		echo "Can't detect the branch automatically, please specify it by using the --branch option." >&2
		exit 1
	fi
}
update() {
	set -e
	NO_RM=false

	while echo "$1" | grep "^-" >/dev/null; do
		case "$1" in
		--zip-url)
			FULL_URI="$2"
			shift 2
			;;
		--no-rm)
			NO_RM=true
			shift
			;;
		--flavour)
			FLAVOUR="$2"
			shift 2
			;;
		--branch)
			BRANCH="$2"
			shift 2
			;;
		--tmp-dir)
			TMP_DIR="$2"
			shift 2
			;;
		-*)
			echo "invalid option: $1" 1>&2
			shift
			;;
		esac
	done

	RELEASE_ROOT=$(dirname "$SCRIPTPATH")
	uri="https://git.pleroma.social"
	project_id="2"
	project_branch="${BRANCH:-$(detect_branch)}"
	flavour="${FLAVOUR:-$(detect_flavour)}"
	tmp="${TMP_DIR:-/tmp}"
	artifact="$tmp/pleroma.zip"
	full_uri="${FULL_URI:-${uri}/api/v4/projects/${project_id}/jobs/artifacts/${project_branch}/download?job=${flavour}}"
	echo "Downloading the artifact from ${full_uri} to ${artifact}"
	curl "$full_uri" -o "${artifact}"
	echo "Unpacking ${artifact} to ${tmp}"
	unzip -q "$artifact" -d "$tmp"
	echo "Copying files over to $RELEASE_ROOT"
	if [ "$NO_RM" = false ]; then
		echo "Removing files from the previous release"
		rm -r "${RELEASE_ROOT:-?}"/*
	fi
	cp -rf "$tmp/release"/* "$RELEASE_ROOT"
	echo "Removing temporary files"
	rm -r "$tmp/release"
	rm "$artifact"
	echo "Done! Please refer to the changelog/release notes for changes and update instructions"
	set +e
}

if [ -z "$1" ] || [ "$1" = "help" ]; then
	# TODO: Just list the commands on `pleroma_ctl help` and output help for the individual command on `pleroma_ctl help $COMMAND`
	echo "Usage: $(basename "$0") COMMAND [ARGS]

    The known commands are:

        create
	  Create database schema (needs to be executed only once)

        migrate
	  Execute database migrations (needs to be done after updates)

        rollback [VERSION]
	  Rollback database migrations (needs to be done before downgrading)

	update [OPTIONS]
	  Update the instance.

	  Options:
	  --branch  Update to a specified branch, instead of the latest version of the current one.
	  --flavour Update to a specified flavour (CPU architecture+libc), instead of the current one.
	  --zip-url Get the release from a specified url. If set, renders the previous 2 options inactive.
	  --no-rm   Do not erase previous release's files.
	  --tmp-dir Download the temporary files to a specified directory.

    and any mix tasks under Pleroma namespace, for example \`mix pleroma.user COMMAND\` is
    equivalent to \`$(basename "$0") user COMMAND\`

    By default pleroma_ctl will try calling into a running instance to execute non migration-related commands,
    if for some reason this is undesired, set PLEROMA_CTL_RPC_DISABLED environment variable.

"
else
	SCRIPT=$(readlink -f "$0")
	SCRIPTPATH=$(dirname "$SCRIPT")

	FULL_ARGS="$*"

	ACTION="$1"
	if [ $# -gt 0 ]; then
		shift
	fi
	echo "$1" | grep "^-" >/dev/null
	if [ $? -eq 1 ]; then
		SUBACTION="$1"
		if [ $# -gt 0 ]; then
			shift
		fi
	fi

	if [ "$ACTION" = "update" ]; then
		update "$@"
	elif [ "$ACTION" = "migrate" ] || [ "$ACTION" = "rollback" ] || [ "$ACTION" = "create" ] || [ "$ACTION $SUBACTION" = "instance gen" ] || [ "$PLEROMA_CTL_RPC_DISABLED" = true ]; then
		"$SCRIPTPATH"/pleroma eval 'Pleroma.ReleaseTasks.run("'"$FULL_ARGS"'")'
	else
		"$SCRIPTPATH"/pleroma rpc 'Pleroma.ReleaseTasks.run("'"$FULL_ARGS"'")'
	fi
fi
