#!/bin/bash

dockerComposeUpdate()
{
    local app_name="$1"
    local flags="$2"
    local norestart="$3"

    local whitelistupdates=false

    if [[ $compose_setup == "default" ]]; then
        local compose_file="docker-compose.yml"
    elif [[ $compose_setup == "app" ]]; then
        local compose_file="docker-compose.$app_name.yml"
    fi

    if [ "$flags" == "install" ]; then
        dockerConfigSetupFileWithData $app_name;
        if [[ $norestart != "norestart" ]]; then
            dockerComposeRestartAfterUpdate $app_name $flags;
        fi
    fi

    if [ "$flags" == "restart" ]; then
        dockerConfigSetupFileWithData $app_name;
        if [[ $norestart != "norestart" ]]; then
            dockerComposeRestartAfterUpdate $app_name $flags;
        fi
    fi

    # Fail2ban specifics
    if [[ "$app_name" == "fail2ban" ]]; then
        local jail_local_file="$containers_dir/$app_name/config/$app_name/jail.local"
        
        if [ -f "$jail_local_file" ]; then
            if runFileOp grep -q "ignoreip = ips_whitelist" "$jail_local_file"; then

                # Whitelist not set up yet
                if runFileOp grep -q "ignoreip = ips_whitelist" "$jail_local_file"; then
                    local result=$(runFileOp sed -i "s/ips_whitelist/$CFG_IPS_WHITELIST/" "$jail_local_file")
                    checkSuccess "Update the IP whitelist for $app_name"
                    local whitelistupdates=true
                fi

                # If the IPs are set up already but need an update
                local current_ip_range=$(grep "ignoreip = " "$jail_local_file" | cut -d ' ' -f 2)
                if [ "$current_ip_range" != "$CFG_IPS_WHITELIST" ]; then
                    local result=$(runFileOp sed -i "s/ignoreip = ips_whitelist/ignoreip = $CFG_IPS_WHITELIST/" "$jail_local_file")
                    checkSuccess "Update the IP whitelist for $app_name"
                    local whitelistupdates=true
                fi
            fi
        fi
    fi
}
