#!/usr/bin/with-contenv bash
# shellcheck shell=bash

mkdir -p /run/plex-temp

# create folders
if [[ ! -d "${PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR}" ]]; then
    mkdir -p "${PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR}"
    if [[ -z ${LSIO_NON_ROOT_USER} ]]; then
        lsiown -R abc:abc /config
    fi
fi

# remove plex pid after unclean stop
if [[ -f "/config/Library/Application Support/Plex Media Server/plexmediaserver.pid" ]]; then
    rm -f "/config/Library/Application Support/Plex Media Server/plexmediaserver.pid"
fi

if [[ -z ${LSIO_NON_ROOT_USER} ]]; then
    # check Library permissions
    PUID=${PUID:-911}
    if [[ ! "$(stat -c %u /config/Library)" == "${PUID}" ]]; then
        echo "Change in ownership detected, please be patient while we chown existing files"
        echo "This could take some time"
        lsiown -R abc:abc \
            /config/Library
    fi

    # set permissions on Plex Transcoder Temp Directory
    PLEX_MEDIA_SERVER_PREFERENCES="${PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR}/Plex Media Server/Preferences.xml"
    if [[ -f "${PLEX_MEDIA_SERVER_PREFERENCES}" ]]; then
        TranscoderTempDirectory='\bTranscoderTempDirectory="([^"]+)"'
        while IFS= read -r line; do
            if [[ ${line} =~ ${TranscoderTempDirectory} ]] && [[ -d "${BASH_REMATCH[1]}" ]]; then
                echo "Setting permissions on ${BASH_REMATCH[1]}"
                lsiown -R abc:abc "${BASH_REMATCH[1]}"
            fi
        done <"${PLEX_MEDIA_SERVER_PREFERENCES}"
    fi

    # permissions (non-recursive) on config root and folders
    lsiown abc:abc \
        /run/plex-temp \
        /config \
        /config/*
fi
