#!/bin/bash

while getopts e:t:u:d:v:p:i: flag; do
   case ${flag} in
      e) EMAIL=${OPTARG} ;;
      t) TAG=${OPTARG} ;;
      u) USERID=${OPTARG} ;;
      d) DESCRIPTION=${OPTARG} ;;
      v) VERSION=${OPTARG} ;;
      p) USER_PATH=${OPTARG} ;;
      i) UNIX_USER_ID=${OPTARG} ;;
   esac
done

tmp_dir=$(mktemp -d -t surfshark-diagnostics-XXXXXXX)

# user settings
cat $USER_PATH/settings* > $tmp_dir/info.txt 2> /dev/null || true
echo $'\n' >> $tmp_dir/info.txt || true
cat $USER_PATH/globals* >> $tmp_dir/info.txt 2> /dev/null || true
echo $'\n' >> $tmp_dir/info.txt || true
echo "App version: $VERSION" >> $tmp_dir/info.txt || true

# network manager devices
echo "XDG_CURRENT_DESKTOP $XDG_CURRENT_DESKTOP" >> $tmp_dir/info.txt || true
echo "DE $DE" >> $tmp_dir/info.txt || true
echo "DESKTOP_SESSION $DESKTOP_SESSION" >> $tmp_dir/info.txt || true
echo "GROUPS $(getent group)" >> $tmp_dir/info.txt

# TODO: connections

# ip routes
ip route show >> $tmp_dir/info.txt 2> /dev/null || true
echo $'\n' >> $tmp_dir/info.txt || true
ip -6 route show >> $tmp_dir/info.txt 2> /dev/null || true
echo $'\n' >> $tmp_dir/info.txt || true
ip rule show >> $tmp_dir/info.txt 2> /dev/null || true
echo $'\n' >> $tmp_dir/info.txt || true
ip -6 rule show >> $tmp_dir/info.txt 2> /dev/null || true
echo $'\n' >> $tmp_dir/info.txt || true

# crash report
cp -R $USER_PATH/Crashpad $tmp_dir/ 2> /dev/null || true

# electron logs
cp -R $USER_PATH/logs $tmp_dir 2> /dev/null || true

zip -r /tmp/surfshark-diagnostics.zip $tmp_dir 2> /dev/null

params=()

if [[ -n $USERID ]]; then
    params+=("-F userId=\"$USERID\"")
fi

if [[ -n $EMAIL  ]]; then
    params+=("-F email=\"$EMAIL\" ")
fi

if [[ -n $TAG  ]]; then
    params+=("-F tag=\"$TAG\"")
fi

if [[ -n $DESCRIPTION  ]]; then
    params+=("-F description=\"$DESCRIPTION\"")
fi

curl 'https://api.surfshark.com/v1/proposal/diagnostics' \
    "${params[@]}" \
    --user-agent "SurfsharkLinux/$VERSION device/desktop" \
    --fail -F file=@/tmp/surfshark-diagnostics.zip

RETUR=$?

rm -rf $tmp_dir
rm /tmp/surfshark-diagnostics.zip

exit $RETUR
