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

# make our folders
mkdir -p \
    /config/www/{avatars,backgrounds,icons,logs,SupportedApps} \
    /config/log/heimdall

# install heimdall if necessary
if [[ -d /app/www-tmp ]]; then
    echo "New container detected, installing Heimdall"
    mv /app/www-tmp /app/www
    cp /app/www/storage/app/searchproviders.yaml /app/www/storage/app/searchproviders.yaml.orig
    touch /app/set-perms
fi

# create symlinks
symlinks=(
    /app/www/storage/app/public/avatars
    /app/www/storage/app/public/backgrounds
    /app/www/storage/app/public/icons
    /app/www/storage/logs
    /app/www/app/SupportedApps
    /app/www/database/app.sqlite
    /app/www/.env
)
for i in "${symlinks[@]}"; do
    if [[ -e "${i}" && ! -L "${i}" ]]; then
        rm -rf "${i}"
    fi
    if [[ ! -L "${i}" ]]; then
        ln -s /config/www/"$(basename "${i}")" "${i}"
    fi
done

# copy searchproviders if not exists and symlink
if [[ ! -f /config/www/searchproviders.yaml ]]; then
    cp /app/www/storage/app/searchproviders.yaml.orig /config/www/searchproviders.yaml
fi
rm -rf /app/www/storage/app/searchproviders.yaml
ln -s /config/www/searchproviders.yaml /app/www/storage/app/searchproviders.yaml

# tidy up install files & set permissions
if [[ -f /app/set-perms ]]; then
    rm -rf /app/set-perms
    lsiown -R abc:abc \
        /app/www \
        /config
fi

# copy .env if not exists
if [[ ! -f /config/www/.env ]]; then
    install -g abc -o abc /app/www/.env.example /config/www/.env
    echo "Creating app key. This may take a while on slower systems"
    s6-setuidgid abc php /app/www/artisan key:generate
fi

# set queue driver to database
sed -i 's/QUEUE_DRIVER=sync/QUEUE_DRIVER=database/' /config/www/.env
