#!/bin/bash
set -e
set -o pipefail

FFMPEG_INSTALL_DIR="/usr/lib/audiobookshelf-ffmpeg"
DEFAULT_DATA_DIR="/usr/share/audiobookshelf"
CONFIG_PATH="/etc/default/audiobookshelf"
DEFAULT_PORT=13378
DEFAULT_HOST="0.0.0.0"

add_user() {
  : "${1:?'User was not defined'}"
  declare -r user="$1"
  declare -r uid="$2"

  if [ -z "$uid" ]; then
    declare -r uid_flags=""
  else
    declare -r uid_flags="--uid $uid"
  fi

  declare -r group="${3:-$user}"
  declare -r descr="${4:-No description}"
  declare -r shell="${5:-/bin/false}"

  if ! getent passwd | grep -q "^$user:"; then
    echo "Creating system user: $user in $group with $descr and shell $shell"
    useradd $uid_flags --gid $group --no-create-home --system --shell $shell -c "$descr" $user
  fi
}

add_group() {
  : "${1:?'Group was not defined'}"
  declare -r group="$1"
  declare -r gid="$2"

  if [ -z "$gid" ]; then
    declare -r gid_flags=""
  else
    declare -r gid_flags="--gid $gid"
  fi

  if ! getent group | grep -q "^$group:" ; then
    echo "Creating system group: $group"
    groupadd $gid_flags --system $group
  fi
}

install_ffmpeg() {
  echo "Starting FFMPEG Install"

  WGET="wget https://johnvansickle.com/ffmpeg/builds/ffmpeg-git-amd64-static.tar.xz --output-document=ffmpeg-git-amd64-static.tar.xz"

  if ! cd "$FFMPEG_INSTALL_DIR"; then
    echo "Creating ffmpeg install dir at $FFMPEG_INSTALL_DIR"
    mkdir "$FFMPEG_INSTALL_DIR"
    chown -R 'audiobookshelf:audiobookshelf' "$FFMPEG_INSTALL_DIR"
    cd "$FFMPEG_INSTALL_DIR"
  fi

  $WGET
  tar xvf ffmpeg-git-amd64-static.tar.xz --strip-components=1 --no-same-owner
  rm ffmpeg-git-amd64-static.tar.xz

  echo "Good to go on Ffmpeg... hopefully"
}

setup_config() {
  if [ -f "$CONFIG_PATH" ]; then
    echo "Existing config found."
    cat $CONFIG_PATH

  else

    if [ ! -d "$DEFAULT_DATA_DIR" ]; then
      # Create directory and set permissions
      echo "Creating default data dir at $DEFAULT_DATA_DIR"
      mkdir "$DEFAULT_DATA_DIR"
      chown -R 'audiobookshelf:audiobookshelf' "$DEFAULT_DATA_DIR"
    fi

    echo "Creating default config."

    config_text="METADATA_PATH=$DEFAULT_DATA_DIR/metadata
CONFIG_PATH=$DEFAULT_DATA_DIR/config
FFMPEG_PATH=$FFMPEG_INSTALL_DIR/ffmpeg
FFPROBE_PATH=$FFMPEG_INSTALL_DIR/ffprobe
PORT=$DEFAULT_PORT
HOST=$DEFAULT_HOST"

    echo "$config_text"

    echo "$config_text" > /etc/default/audiobookshelf;

    echo "Config created"
  fi
}

add_group 'audiobookshelf' ''

add_user 'audiobookshelf' '' 'audiobookshelf' 'audiobookshelf user-daemon' '/bin/false'

setup_config

install_ffmpeg
