#!/bin/bash

# Category : Productivity
# Description : MoneyApp - Self-hosted household money management (c/u/s/r/i):

installMoneyapp()
{
    local config_variables="$1"

    if [[ "$moneyapp" == *[cCtTuUsSrRiI]* ]]; then
        dockerConfigSetupToContainer silent moneyapp;
        local app_name=$CFG_MONEYAPP_APP_NAME
        initializeAppVariables $app_name;
    fi

    if [[ "$moneyapp" == *[cC]* ]]; then
        editAppConfig $app_name;
    fi

    if [[ "$moneyapp" == *[uU]* ]]; then
        dockerUninstallApp $app_name;
    fi

    if [[ "$moneyapp" == *[sS]* ]]; then
        dockerComposeDown $app_name;
    fi

    if [[ "$moneyapp" == *[rR]* ]]; then
        dockerComposeRestart $app_name;
    fi

    if [[ "$moneyapp" == *[iI]* ]]; then
        isHeader "Install $app_name"

        # Pre-flight: bail out before touching any compose/config if the
        # global prerequisites aren't met. CFG_MONEYAPP_REQUIRES lists
        # what's needed (currently "domain,traefik"); the helper prints a
        # clear list of what's missing so the user knows what to fix.
        if ! appInstallCheckRequirements "$app_name" "$CFG_MONEYAPP_REQUIRES"; then
            moneyapp=n
            return 1
        fi

        ((menu_number++))
        echo ""
        echo "---- $menu_number. Setting up install folder and config file for $app_name."
        echo ""

        dockerConfigSetupToContainer "loud" "$app_name" "install" "$config_variables";
        isSuccessful "Install folders and Config files have been setup for $app_name."

        ((menu_number++))
        echo ""
        echo "---- $menu_number. Setting up the $app_name docker-compose.yml file."
        echo ""

        dockerComposeSetupFile $app_name;

        ((menu_number++))
        echo ""
        echo "---- $menu_number. Resolving Auth.js callback URL (AUTH_URL)."
        echo ""

        # Auth.js requires a fixed AUTH_URL that matches what the browser
        # actually hits — otherwise OAuth-style callbacks bounce. We pick:
        #   * https://<host>.<domain>     when traefik is on AND a real
        #                                  domain is configured (CFG_DOMAIN_<n>)
        #   * http://<server-ip>:<port>   otherwise (raw port exposure)
        local moneyapp_compose_file="$containers_dir$app_name/docker-compose.yml"
        local moneyapp_auth_url=""
        # `host_setup` is built as `<app>.<domain>` — when CFG_DOMAIN_<n> is
        # empty it ends up as `<app>.` which is a valid-but-broken hostname.
        # Reject that explicitly: we want a real TLD before going https.
        local _has_real_domain=0
        if [[ -n "$host_setup" && "$host_setup" != *. ]] && [[ "$host_setup" == *.* ]]; then
            _has_real_domain=1
        fi
        if [[ "$public" == "true" && $_has_real_domain -eq 1 ]]; then
            moneyapp_auth_url="https://$host_setup"
        else
            local moneyapp_port_pair
            moneyapp_port_pair=$(tagsManagerGetTagContent "$moneyapp_compose_file" "PORTS_TAG_1")
            local moneyapp_external_port="${moneyapp_port_pair%%:*}"
            local moneyapp_host="${public_ip_v4:-localhost}"
            moneyapp_auth_url="http://${moneyapp_host}:${moneyapp_external_port}"
            if [[ "$public" == "true" && $_has_real_domain -eq 0 ]]; then
                isNotice "PORT_1 has traefik=true but no domain configured — falling back to direct port URL."
            fi
        fi
        tagsManagerUpdateUniversalTag "$moneyapp_compose_file" "MONEYAPP_AUTH_URL_TAG" "$moneyapp_auth_url"
        isSuccessful "AUTH_URL set to $moneyapp_auth_url"

        ((menu_number++))
        echo ""
        echo "---- $menu_number. Updating file permissions before starting."
        echo ""

        fixPermissionsBeforeStart $app_name;

        ((menu_number++))
        echo ""
        echo "---- $menu_number. Running the docker-compose.yml to install and start $app_name"
        echo ""

        dockerComposeUpdateAndStartApp $app_name install;

        ((menu_number++))
        echo ""
        echo "---- $menu_number. Running Application specific updates (if required)"
        echo ""

        appUpdateSpecifics $app_name;

        ((menu_number++))
        echo ""
        echo "---- $menu_number. Running Headscale setup (if required)"
        echo ""

        setupHeadscale $app_name;

        ((menu_number++))
        echo ""
        echo "---- $menu_number. Adding $app_name to the Apps Database table."
        echo ""

        databaseInstallApp $app_name;

        ((menu_number++))
        echo ""
        echo "---- $menu_number. Updating the WebUI config file."
        echo ""

        webuiContainerSetup $app_name install;

        ((menu_number++))
        echo ""
        echo "---- $menu_number. You can find $app_name files at $containers_dir$app_name"
        echo ""
        echo "    First account to sign up becomes the household owner."
        echo ""

        menuShowFinalMessages "$app_name";

        menu_number=0
        cd
    fi
    moneyapp=n
}
