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

if [ ! -f /started ]; then

touch /started

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

ha_entry_source=true

candidate_shebangs+=(
    "/usr/bin/env bashio"
    "/usr/bin/bashio"
    "/usr/bin/bash"
    "/usr/bin/sh"
    "/bin/bash"
    "/bin/sh"
)

# Find the first valid shebang interpreter in candidate list
shebang=""
for candidate in "${candidate_shebangs[@]}"; do
    command_path="${candidate%% *}"
    # Test if command exists and can actually execute a shell command (for shells)
    if [ -x "$command_path" ]; then
        # Try as both 'sh -c' and 'bashio echo' style
        if "$command_path" -c 'echo yes' > /dev/null 2>&1 || "$command_path" echo "yes" > /dev/null 2>&1; then
            shebang="$candidate"
            break
        fi
    fi
done
if [ -z "$shebang" ]; then
    echo "ERROR: No valid shebang found!"
    exit 1
fi

for SCRIPTS in /etc/cont-init.d/*; do
    [ -e "$SCRIPTS" ] || continue
    echo "$SCRIPTS: executing"

    # Check if run as root (UID 0)
    if [ "$(id -u)" -eq 0 ]; then
        # Fix permissions for root user
        chown "$(id -u)":"$(id -g)" "$SCRIPTS"
        chmod a+x "$SCRIPTS"
    else
        echo -e "\e[38;5;214m$(date) WARNING: Script executed with user $(id -u):$(id -g), things can break and chown won't work\e[0m"
        # Disable chown and chmod commands inside the script for non-root users
        sed -i "s/^\s*chown /true # chown /g" "$SCRIPTS"
        sed -i "s/^\s*chmod /true # chmod /g" "$SCRIPTS"
    fi

    # Prepare to run
    sed -i "1s|^.*|#!$shebang|" "$SCRIPTS"
    chmod +x "$SCRIPTS"

    # Optionally use 'source' to share env variables, when requested
    if [ "${ha_entry_source:-null}" = true ]; then
        # Replace exit with return, so sourced scripts can return errors
        sed -i -E 's/^\s*exit ([0-9]+)/return \1 \|\| exit \1/g' "$SCRIPTS"
        sed -i 's/bashio::exit\.nok/return 1/g' "$SCRIPTS"
        sed -i 's/bashio::exit\.ok/return 0/g' "$SCRIPTS"
        # shellcheck disable=SC1090
        source "$SCRIPTS" || echo -e "\033[0;31mError\033[0m : $SCRIPTS exiting $?"
    else
        "$SCRIPTS" || echo -e "\033[0;31mError\033[0m : $SCRIPTS exiting $?"
    fi

    # Cleanup after execution
    sed -i '1a exit 0' "$SCRIPTS"
done

####################
# 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"

if bashio::config.has_value "FORWARDED_ALLOW_IPS"; then
    export FORWARDED_ALLOW_IPS="$(bashio::config "FORWARDED_ALLOW_IPS")"
    bashio::log.info "Configured FORWARDED_ALLOW_IPS for Gunicorn"
fi

# Unset allow_signup

if bashio::config.false "ALLOW_SIGNUP"; then
  echo "ALLOW_SIGNUP is deactivated"
  unset ALLOW_SIGNUP
fi

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

bashio::log.info "Starting app"
fi
