#!/bin/bash
# -*- mode: sh; tab-width: 8; encoding: utf-8-unix -*-

ROLE=proxy
PREFIX=/usr/local

. /usr/local/bin/usr_local_tput.bash || exit 2

ip route | grep -q ^def || {
    WARN we are not connected >&2
    exit 1
}

[ -f $HOME/.curlrc ] || touch $HOME/.curlrc

declare -a CURL_OPTS
# --silent  --show-error
CURL_OPTS=( --fail-early --fail )

[[ "$*" =~ --http0.9 ]] || [[ "$*" =~ --http1 ]] || [[ "$*" =~ --http1.1 ]] || \
  [[ "$*" =~ --http2 ]] || [[ "$*" =~ --http3 ]] ||  CURL_OPTS+=( --http0.9 )
[[ ! "$*" =~ --retry ]] &&  CURL_OPTS+=( --retry 3 )
[[ ! "$*" =~ -4 ]] &&  CURL_OPTS+=( -4 )
# [[ ! "$*" =~ --http2 ]] &&  CURL_OPTS+=(  --http2 )
[[ ! "$*" =~  --max-redirs ]] &&  CURL_OPTS+=( --max-redirs 10 )
[[ ! "$*" =~ --location ]] &&  CURL_OPTS+=( --location )
[[ ! "$*" =~ --remote-time ]] &&  CURL_OPTS+=( --remote-time )
[[ ! "$*" =~ --create-dirs ]] &&  CURL_OPTS+=( --create-dirs )

if [[ "$socks_proxy" =~ socks5://.* ]] ; then
    export socks_proxy="$( echo $socks_proxy | sed -e 's@socks5://@socks5h://@' )"
fi

if [[ ! "$*" =~  --proxy ]] && [ -n "$socks_proxy" ] ; then
    CURL_OPTS+=( --proxy $socks_proxy )
    [ -n "$https_proxy" ] && export https_proxy= && unset https_proxy
    [ -n "$http_proxy" ]  && export http_proxy=  && unset http_proxy
  elif [ -n "$https_proxy" ] ; then
    CURL_OPTS+=( --proxy $https_proxy )
    [ -n "$http_proxy" ] && export http_proxy= && unset http_proxy
  elif [ -n "$http_proxy" ] ; then
    CURL_OPTS+=( --proxy $http_proxy )
fi
export CURL_OPTS+=( -L )

if [ -d  $HOME/.local/ ] ; then
    [ -f $HOME/.local/jar.cookie ] || touch $HOME/.local/jar.cookie
    [[ ! "$*" =~ --cookie-jar ]] && \
        CURL_OPTS+=(  --cookie-jar $HOME/.local/jar.cookie --junk-session-cookies )
fi

if ! uname -a | grep -q 'Devuan\|Debian' && [ -s $HOME/.local/alt.svc ] ; then
    export CURL_OPTS+=( --alt-svc $HOME/.local/alt.svc )
    # #define CURLALTSVC_H2           (1<<4)
    export CURLOPT_ALTSVC_CTRL=16
fi

[[ ! "$*" =~ --config ]] && [ -s "$HOME/.curlrc" ] && \
    export CURL_OPTS+=( --config $HOME/.curlrc )
[[ ! "$*" =~ --cookie-jar ]] && [ -s $HOME/.local/jar.cookie ] && \
  export CURL_OPTS+=( --cookie-jar $HOME/.local/jar.cookie )
if [[ ! "$*" =~ --capath ]] && \
       [[ ! "$*" =~ --cacert  ]] && \
       [ -s /usr/local/etc/ssl/cacert-testforge.pem ] ; then
    # --capath /usr/local/etc/:/etc/ssl/certs
  export CURL_OPTS+=( --cacert /usr/local/etc/ssl/cacert-testforge.pem )
  export CURL_CA_BUNDLE=/usr/local/etc/ssl/cacert-testforge.pem
fi

export CURL_OPTS
DBUG /usr/bin/curl "${CURL_OPTS[@]}" "$@" >&2
exec /usr/bin/curl "${CURL_OPTS[@]}" "$@"
