#!/nix/store/izpf49b74i15pcr9708s3xdwyqs4jxwl-bash-5.2p32/bin/bash
set -e
mkdir -p /var/lib/hydra
chown hydra:hydra /var/lib/hydra
chmod 0750 /var/lib/hydra

ln -sf /nix/store/yx73zabjkx9ynhsg3ryzarhkg6gyvdhh-hydra.conf /var/lib/hydra/hydra.conf

mkdir -m 0700 -p /var/lib/hydra/www
chown hydra-www:hydra /var/lib/hydra/www

mkdir -m 0700 -p /var/lib/hydra/queue-runner
mkdir -m 0750 -p /var/lib/hydra/build-logs
mkdir -m 0750 -p /var/lib/hydra/runcommand-logs
chown hydra-queue-runner:hydra \
  /var/lib/hydra/queue-runner \
  /var/lib/hydra/build-logs \
  /var/lib/hydra/runcommand-logs

if ! [ -e /var/lib/hydra/.db-created ]; then
  runuser -u postgres /nix/store/5r7nk7yzxx2m4h72zpab7wpplfxs6ngx-postgresql-15.8/bin/createuser hydra
  runuser -u postgres /nix/store/5r7nk7yzxx2m4h72zpab7wpplfxs6ngx-postgresql-15.8/bin/createdb -- -O hydra hydra
  touch /var/lib/hydra/.db-created
fi
echo "create extension if not exists pg_trgm" | runuser -u postgres -- /nix/store/5r7nk7yzxx2m4h72zpab7wpplfxs6ngx-postgresql-15.8/bin/psql hydra


if [ ! -e /nix/var/nix/gcroots/hydra ]; then

  # Move legacy roots directory.
  if [ -e /nix/var/nix/gcroots/per-user/hydra/hydra-roots ]; then
    mv /nix/var/nix/gcroots/per-user/hydra/hydra-roots /nix/var/nix/gcroots/hydra
  fi

  mkdir -p /nix/var/nix/gcroots/hydra
fi

# Move legacy hydra-www roots.
if [ -e /nix/var/nix/gcroots/per-user/hydra-www/hydra-roots ]; then
  find /nix/var/nix/gcroots/per-user/hydra-www/hydra-roots/ -type f \
    | xargs -r mv -f -t /nix/var/nix/gcroots/hydra/
  rmdir /nix/var/nix/gcroots/per-user/hydra-www/hydra-roots
fi

chown hydra:hydra /nix/var/nix/gcroots/hydra
chmod 2775 /nix/var/nix/gcroots/hydra


