#!/bin/bash

## Init is run on host
## For now it is run every time the script is launched, but
## it should be launched only once after build.

## Accessible variables are:
## - SERVICE_NAME        Name of current service
## - DOCKER_BASE_IMAGE   Base image from which this service might be built if any
## - SERVICE_DATASTORE           Location on host of the DATASTORE of this service
## - SERVICE_CONFIGSTORE         Location on host of the CONFIGSTORE of this service

set -e

peertube_uid=$(docker_get_uid "$SERVICE_NAME" "peertube")

PEERTUBE_APP_DIR=/opt/apps/peertube
PEERTUBE_DATA_DIR=/var/lib/peertube
PEERTUBE_LOG_DIR=/var/log/peertube
PEERTUBE_CACHE_DIR=/var/cache/peertube
PEERTUBE_CONFIG_DIR=/etc/peertube

HOST_CONFIG_DIR=$SERVICE_CONFIGSTORE/$PEERTUBE_CONFIG_DIR
HOST_DATA_DIR=$SERVICE_DATASTORE/$PEERTUBE_DATA_DIR


mkdir -p "$HOST_CONFIG_DIR"

## Always copy default and custom env configuration file, in cases where new keys were added
ln -sf "$PEERTUBE_APP_DIR"/config/default.yaml "$HOST_CONFIG_DIR"


cat <<EOF > "$HOST_CONFIG_DIR/local.yaml"

listen:
  hostname: '0.0.0.0'
  port: 9000

storage:

  avatars: '$PEERTUBE_DATA_DIR/avatars/'
  videos: '$PEERTUBE_DATA_DIR/videos/'
  redundancy: '$PEERTUBE_DATA_DIR/redundancy/'
  previews: '$PEERTUBE_DATA_DIR/previews/'
  thumbnails: '$PEERTUBE_DATA_DIR/thumbnails/'
  torrents: '$PEERTUBE_DATA_DIR/torrents/'
  captions: '$PEERTUBE_DATA_DIR/captions/'

  logs: '/var/log/peertube/'

  cache: '/var/cache/peertube/'
  tmp: '/var/tmp/peertube/'

EOF


VALID_SECTION=(
    instance services import transcoding
    user signup admin cache redundancy
    trending search log
)
for section in "${VALID_SECTION[@]}"; do
    if val=$(options-get "$section" 2>/dev/null); then
        yaml_key_val_str "$section" "$val"
    fi
done >> "$HOST_CONFIG_DIR/local.yaml"

if ! [ -e "$HOST_DATA_DIR/config.json" ]; then
    echo "{}" > "$HOST_DATA_DIR/config.json"
fi

ln -sf "$PEERTUBE_DATA_DIR"/config.json "$HOST_CONFIG_DIR/local-prod.json"


dirs=(/var/tmp/peertube /var/cache/peertube
      "$PEERTUBE_CACHE_DIR" "$PEERTUBE_LOG_DIR" "$PEERTUBE_DATA_DIR")
host_dirs=()
for dir in "${dirs[@]}"; do
    host_dirs+=("$SERVICE_DATASTORE$dir")
done

mkdir -p "${host_dirs[@]}"
find "${host_dirs[@]}" \! -user "$peertube_uid" -print0 | while read-0 f; do
    chown -v "$peertube_uid" "$f" || exit 1
done

true