#!/bin/bash

source /opt/scripts_local/shared_functions.sh

APP_NAME=filebrowser

if ! _isServiceRunning "$APP_NAME" && ! [ -f /etc/systemd/system/"$APP_NAME".service ] ;
then
  APP_DESCRIPTION="File Browser Service"
  APP_DIR="/opt/$APP_NAME"
  APP_SERVICE="/etc/systemd/system/$APP_NAME.service"
  sudo curl -fsSL https://raw.githubusercontent.com/filebrowser/get/master/get.sh | bash

  sudo groupadd --system "$APP_NAME" >/dev/null 2>&1
  sudo useradd --system \
    --gid "$APP_NAME" \
    --create-home \
    --home-dir "/var/lib/$APP_NAME" \
    --shell /usr/sbin/nologin \
    --comment "$APP_DESCRIPTION" \
    "$APP_NAME" >/dev/null 2>&1
  sudo mkdir -p "$APP_DIR" "var/log/$APP_NAME"
  sudo chown "$APP_NAME":"$APP_NAME" "$APP_DIR"
  sudo chmod 770 "$APP_DIR" 
  sudo chown "$APP_NAME":"$APP_NAME" -R "/usr/local/bin/$APP_NAME" "/opt/$APP_NAME" /var/log/"$APP_NAME"
  sudo rm "$APP_SERVICE" >/dev/null 2>&1
  download_template  "/mnt/union/shared/$APP_NAME" "$APP_SERVICE"
  sudo chmod 700 "$APP_SERVICE"
  sudo systemctl daemon-reload
  sudo systemctl enable --now "$APP_NAME"
fi