#!/bin/sh
# Prepare a fresh installation identity. Existing installations use backup/upgrade instead.
set -eu

refuse() { printf '%s\n' "$1" >&2; exit 1; }

[ "$#" -le 1 ] || refuse 'Usage: sh prepare-fresh-install.sh [new-project-name]'
[ -f compose.yaml ] && [ ! -L compose.yaml ] || refuse 'Run beside the downloaded compose.yaml.'
[ ! -e .env ] && [ ! -L .env ] || refuse 'An .env already exists. Keep it and follow the backup/upgrade guide; do not prepare this directory again.'
for value in "${COMPOSE_PROJECT_NAME-}" "${COMPOSE_FILE-}" "${COMPOSE_ENV_FILES-}" "${COMPOSE_DISABLE_ENV_FILE-}"; do
  [ -z "$value" ] || refuse 'Compose environment overrides are set. Use a clean shell for a fresh installation; keep existing installations on their original configuration.'
done

project=${1:-teloa-$(date -u +%Y%m%d%H%M%S)-$$}
case "$project" in ''|teloa|[-_]*|*[!a-z0-9_-]*) refuse 'Choose a new lowercase project name; the legacy name teloa is reserved for existing installations.';; esac

docker info >/dev/null
docker compose version >/dev/null
containers=$(docker ps -a --filter "label=com.docker.compose.project=$project" --format '{{.ID}}')
[ -z "$containers" ] || refuse 'This project already has containers. Use its original directory and backup/upgrade procedure.'
labelled_volumes=$(docker volume ls --filter "label=com.docker.compose.project=$project" --format '{{.Name}}')
[ -z "$labelled_volumes" ] || refuse 'This project already has data volumes. Do not create a fresh installation over them.'
volumes=$(docker volume ls --format '{{.Name}}')
for volume in $volumes; do
  case "$volume" in "${project}_"*) refuse 'Volumes with this project prefix already exist. Choose another new project name.';; esac
done
networks=$(docker network ls --filter "label=com.docker.compose.project=$project" --format '{{.ID}}')
[ -z "$networks" ] || refuse 'This project already has a network. Choose another new project name.'

# Exclusive creation also protects against a concurrent preparation or a dangling symlink.
umask 077
(set -C; printf 'COMPOSE_PROJECT_NAME=%s\n' "$project" > .env)
printf 'Prepared new project %s. Keep .env for later start, backup and upgrade commands.\n' "$project"
