SHELL = /bin/sh

# © 2023 Lady [@ Lady’s Computer].
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

# This Makefile requires rsync 3 or newer.
RSYNC = rsync
RSYNC_FLAGS = -Oclmrtvz
RSYNC_OPTIONS =
RSYNC_FILTER = .rsync-filter

SOURCE_CHARSET = utf-8-mac

DESTINATION_HOST = computer
DESTINATION_PATH = lady/www
DESTINATION = $(DESTINATION_HOST):$(DESTINATION_PATH)
DESTINATION_CHARSET = utf-8

GIT_FORCE =

build:
# Put any necessary build scripts in here!
	touch .grass

ensure-build:
	@if [ ! -f .grass ]; then echo 'Error: The website has not been built yet!' >&2; echo 'Run `make` before syncing.' >&2; exit 1; fi
	@if buildtime=$$(stat -f '%m' .grass) && committime=$$(git log -1 --format='%ct' | awk '{print $$NF}') && [ "$$committime" -gt "$$buildtime" ]; then echo 'Error: A commit was made after the last build!' >&2; echo 'Run `make` before syncing.' >&2; exit 1; fi

ensure-branch-up-to-date:
	git fetch
	@if ! git merge-base --is-ancestor @{u} HEAD; then echo 'Error: This branch is currently out‐of‐date!' >&2; echo 'Pull in changes with `git pull` before syncing.' >&2; exit 1; fi

ensure-clean:
	@if output=$$(git status --porcelain) && [ ! -z "$$output" ]; then echo 'Error: There are uncommitted changes!' >&2; echo 'Commit changes and run `make` before syncing.' >&2; exit 1; fi

dry-sync: ensure-clean$(if $(GIT_FORCE),, ensure-branch-up-to-date) ensure-build
	$(RSYNC) $(RSYNC_FLAGS) --del --dry-run --filter=". $(RSYNC_FILTER)" --iconv=$(SOURCE_CHARSET),$(DESTINATION_CHARSET) $(RSYNC_OPTIONS) . $(DESTINATION)

sync: ensure-clean$(if $(GIT_FORCE),, ensure-branch-up-to-date) ensure-build
	$(RSYNC) $(RSYNC_FLAGS) --del --filter=". $(RSYNC_FILTER)" --iconv=$(SOURCE_CHARSET),$(DESTINATION_CHARSET) $(RSYNC_OPTIONS) . $(DESTINATION)
	git push$(if $(GIT_FORCE), --force,)

.PHONY: build dry-sync ensure-branch-up-to-date ensure-build ensure-clean sync;