#!/bin/sh # TODO : # - add root user detection # - verify curl output to prevent overwriting config file with an HTTP answer _usage() { echo " Usage: $0 --url [options...] Commands : -d, --download only download config file -i, --install download config file and install the service (UNIMPLEMENTED) Parameters: -u, --url Specify your WG Portal base URL -f, --filename Specify Wireguard filename (default: /etc/wireguard/wg0.conf) " _version } _version() { printf "%s version pre-alpha 0.1 (yes we're very cautious)\n" "$0" printf "USE AT YOUR OWN RISK and read the code before\n" } _startswith() { _str="$1" _sub="$2" echo "$_str" | grep "^$_sub" >/dev/null 2>&1 } _download() { [ -z "$WGPORTAL_URL" ] && printf "Please set wg-portal URL (see help)\n" && return 1 [ -z "$WG_CONFFILE" ] && WG_CONFFILE=/etc/wireguard/wg0.conf trap 'stty echo; exit 99;' INT if [ -f $WG_CONFFILE -a "$OVERWRITE" != "on" ]; then printf "WARNING : Wireguard config file already exists\n" printf "Exiting now to prevent overrid of your actual parameters\n" printf "You can force config overwriting with :\n" printf "OVERWRITE=on %s %s\n" "$0" "$_ARGS" exit 1; fi printf "Username: " IFS= read -r username printf "Password: " stty -echo IFS= read -r password stty echo printf "\n" printf "Peer public key: " IFS= read -r wgpubkey printf "\n" HTTP_STATUS=$(curl -w "%{http_code}" -G -s -o $WG_CONFFILE --user $username:$password --data-urlencode "pkey=$wgpubkey" -X GET $WGPORTAL_URL"api/v1/provisioning/peer" -H "accept: text/plain") res=$? if [ "$res" != "0" ]; then echo "the curl command failed with: $res" fi [ $HTTP_STATUS -ne 200 ] && printf "Curl returned HTTP code %s\n" "$HTTP_STATUS" && exit 1 printf "WG config successfully download at %s\n" "$WG_CONFFILE" } _install() { printf "install : This command does nothing ... yet (TDB)\n" } _process() { while [ ${#} -gt 0 ]; do case "${1}" in --help | -h) _usage return ;; --version | -v) _version return ;; --download | -d) _CMD="download" ;; --url | -u) WGPORTAL_URL="$2" shift ;; --filename | -f) WG_CONFFILE="$2" shift ;; --install | -i) _CMD="install" ;; *) printf "Unknown parameter : %s\n" "$1" return 1 ;; esac shift 1 done case "${_CMD}" in download) _download ;; install) _install ;; *) if [ "$_CMD" ]; then printf "Invalid command: %s\n" "$_CMD" fi esac } main() { [ -z "$1" ] && _usage && return if _startswith "$1" '-'; then _process "$@"; else "$@"; fi } _ARGS="$*" main "$@"