#!/command/with-contenv bash

# Change runtime user UID and GID
groupmod -o -g "${PGID:=911}" app
usermod -o -u "${PUID:=911}" app

# Ensure /config directories exist
mkdir -v -p /config/{cache,media,state,tasks,tubesync}

# Copy local_settings.py for the user
if [ -f /config/tubesync/local_settings.py ]
then
    # from the image for an example or comparison
    cp -v -p /app/tubesync/local_settings.py \
        /config/tubesync/local_settings.py.image

    # to the image to apply the user's settings
    cp -v -p /config/tubesync/local_settings.py \
        /app/tubesync/local_settings.py
fi

# Reset permissions
chown -R app:app /run/app
chmod -R 0700 /run/app
chown -R app:app /config
chmod -R 0755 /config
chown -R root:app /app
chmod -R 0750 /app
chmod 0755 /app/*.py /app/*.sh
find /app -mindepth 2 -type f -execdir chmod 640 '{}' +
chown -R app:app /app/common/static
chown -R app:app /app/static

# Optionally reset the download dir permissions
if [ "${TUBESYNC_RESET_DOWNLOAD_DIR:=True}" == "True" ]
then
    export TUBESYNC_RESET_DOWNLOAD_DIR
    echo "TUBESYNC_RESET_DOWNLOAD_DIR=True, Resetting /downloads directory permissions"
    chown -R app:app /downloads
    chmod -R 0755 /downloads
fi

if [ 'True' = "${TUBESYNC_DEBUG:-False}" ]
then
    s6-setuidgid app \
        /usr/bin/python3 /app/manage.py \
            showmigrations -v 3 --list
fi

# Run migrations
exec s6-setuidgid app \
    /usr/bin/python3 /app/manage.py migrate
