#!/bin/bash

set -e

version_lt() { test "$(printf '%s\n' "$@" | (sort -V || sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n;) | tail -n 1)" != "$1"; }

# run command at repo root
CURRENT_PATH=$PWD
if [ -d .git ]; then
  cd "$(git rev-parse --show-toplevel)"
fi

if ! type yarn > /dev/null; then
  cat << EOF
FATAL: Yarn could not be found.

Run 'corepack enable', then try this script again.
If 'corepack' is not available, try 'npm i -g corepack' first.

For more information, see the installation instructions at
https://yarnpkg.com/getting-started/install
EOF
  exit 1
fi

if version_lt "$(node --version)" 'v16.0.0'; then
  cat << EOF
FATAL: Your Node.js version is not supported.

Please upgrade to version 16 or higher and try again.
We recommend running the latest LTS release, see https://nodejs.org/en/about/releases/ for details.
EOF
  exit 1
fi

echo "Copying config files..."
if [ ! -f config.json ]; then
  cp config.json.example config.json
fi

echo "Installing packages..."
yarn workspaces focus --production

cat << EOF
If you want to build the frontend yourself, you need to run 'yarn install --immutable' before 'yarn build' to install the devDependencies for the build process.

Edit the following config file to setup HedgeDoc server and client.
Read more info at https://docs.hedgedoc.org/configuration/

* config.json           -- HedgeDoc config
EOF

# change directory back
cd "$CURRENT_PATH"
