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

ROLE=proxy

ip route | grep -q ^def || {
    WARN we are not connected
}

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

declare -a CURL_OPTS
if [[ "$socks_proxy" =~ socks5://.* ]] ; then
    export socks_proxy="$( echo $socks_proxy | sed -e 's@socks5://@socks5h://@' )"
    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 --remote-time )
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

echo INFO: curl $CURL_OPTS "$@"
exec       curl $CURL_OPTS "$@"
