#!/bin/sh

set -e


PUID=${PUID:-1000}
PGID=${PGID:-1000}

echo "Starting with UID=$PUID, GID=$PGID"

WRITABLE_DIRS="/app/covers /app/libraries"

# Modify user PGID and PUID to match ther user on the host
if [ "$PUID" != "1000" ] || [ "$PGID" != "1000" ]; then
    echo "Adjusting user to UID=$PUID, GID=$PGID"
    groupmod -o -g "$PGID" appuser
    usermod -o -u "$PUID" appuser


    # Update permissions on writable directories
    for dir in $WRITABLE_DIRS; do
        if [ -d "$dir" ]; then
            echo "Fixing permissions for $dir"
            chown -R appuser:appuser "$dir"
            chmod -R 755 "$dir"
        else
            echo "Creating $dir"
            mkdir -p "$dir"
            chown -R appuser:appuser "$dir"
            chmod -R 755 "$dir"
        fi
    done
fi

echo "Running database migrations..."
alchemy --config chitai.database.config.config upgrade --no-prompt

echo "Starting application..."
exec gosu appuser "$@"
