#!/usr/bin/env bashio
# shellcheck shell=bash
set -e

if [ ! -f /started ]; then

touch /started

####################
# Starting scripts #
####################

for SCRIPTS in /etc/cont-init.d/*; do
    [ -e "$SCRIPTS" ] || continue
    echo "$SCRIPTS: executing"
    chown "$(id -u)":"$(id -g)" "$SCRIPTS"
    chmod a+x "$SCRIPTS"
    # Change shebang if no s6 supervision
    sed -i 's|/usr/bin/with-contenv bashio|/usr/bin/env bashio|g' "$SCRIPTS"
    sed -i "/exit 0/d" "$SCRIPTS"
    . "$SCRIPTS" || echo -e "\033[0;31mError\033[0m : $SCRIPTS exiting $?"
    rm "$SCRIPTS"
done

rm /.env || true
rm /env.py || true

####################
# MIGRATE DATA DIR #
####################

# Migrate files
if [ -d /homeassistant/addons_config/mealie_data ] && [ ! -f /homeassistant/addons_config/mealie_data/migrated ]; then
    bashio::log.warning "Migrating data, current data will not be touched"
    cp -rnf /homeassistant/addons_config/mealie_data/* /config/ || true
    touch /homeassistant/addons_config/mealie_data/migrated
    bashio::addon.option "DATA_DIR" "/config"
fi
if [ -f /homeassistant/addons_config/mealie/config.yaml ] && [ ! -f /homeassistant/addons_config/mealie/migrated ]; then
    bashio::log.warning "Migrating config.yaml, current data will not be touched"
    cp -nf /homeassistant/addons_config/mealie/config.yaml /config/ || true
    touch /homeassistant/addons_config/mealie/migrated
    bashio::addon.option "DATA_DIR" "/config"
fi

# Solve issues in migration
if [ -d /config/recipes ] && [ -d /config/backups ]; then
    [ -d /config/addons_config ] && rm -r /config/addons_config && bashio::log.warning "Deleted /config/addons_config, it shouldn't be there"
    [ -d /config/addons_autoscripts ] && rm -r /config/addons_autoscripts && bashio::log.warning "Deleted /config/addons_autoscripts, it shouldn't be there"
fi
if [[ "$(bashio::config "DATA_DIR")" == "/config/addons_config/mealie_data" ]]; then
    bashio::addon.option "DATA_DIR" "/config"
    bashio::addon.restart
fi

###############
# PERMISSIONS #
###############

chmod -R 777 /data
mkdir -p "$DATA_DIR"
cd "$DATA_DIR" || true
chown -R "$(bashio::config "PUID"):$(bashio::config "PGID")" .
echo "Permissions adapted"

bashio::log.info "Starting nginx"
nginx & true

bashio::log.info "Starting app"
fi
