#!/bin/bash

set -e

SCRIPT_DIR="$(realpath "$(dirname "$0")")"
REPOSITORY="$SCRIPT_DIR"

if [ -n "$REPOSITORY" ]; then
  if [ ! -d "$REPOSITORY" ]; then
    echo "The directory '$REPOSITORY' does not exist." >&2
    eixt 1
  fi
else
  echo "The env variable 'REPOSITORY' is not set or is empty." >&2
  eixt 1
fi

if [ ! -f /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh ]; then
  temp="$(mktemp)"
  curl -L https://nixos.org/nix/install > "$temp"
  sh "$temp" --daemon --yes
  rm -f "$temp"
fi

if ! command -v nix >/dev/null 2>&1; then
  # add nix to shell
  . /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
fi

TG_BOT_NAME="photoedit-bot"

cd "$REPOSITORY"

start_service() {
  service="$1"
  nix --extra-experimental-features "nix-command flakes" build ".#systemdService.${service}"
  sudo cp "result" "/etc/systemd/system/${service}.service"
  sudo systemctl daemon-reload
  sudo systemctl enable "${service}.service"
  sudo systemctl restart "${service}.service"
}

start_service "${TG_BOT_NAME}"

