#!/bin/bash

source common.sh
# shellcheck source=./config.sh
source "$SLACK_BACKUP_CONFIG"

if [[ $SLACK_BACKUP_DEBUG -gt 0 ]]; then
  set -x
fi

# try to get new cookie from server
mkdir -p cookies
if [[ ! -f "cookies/$team_name.jar" ]]; then
  echo "# generated by t-tran/slack-chat-backup" > "cookies/$team_name.jar"
  for c in ${cookie//;/ /} ; do
    c=$(echo "$c" | awk -F= '{print $1"\t"$2}')
    echo -e ".slack.com\tTRUE\t/\tTRUE\t0\t$c" >> "cookies/$team_name.jar"
  done

  make-request --location "https://$team_name.slack.com/" \
  --cookie-jar "cookies/$team_name.jar" \
  >/dev/null 2>/dev/null
fi

x_version_ts=${x_version_ts:-$(date +%s)}
x_id=${x_id:-$(echo "$x_version_ts" | md5sum | cut -c -8)}
x_ts=$(gdate +%s.%3N)

mkdir -p meta/$team_name
mkdir -p log/$team_name
echo "Loading my own profile.."
attempt=1
while true ; do
  make-request "https://$team_name.slack.com/api/client.boot?_x_id=noversion-$x_ts&_x_version_ts=noversion&_x_gantry=true" \
  --header "Host: ${team_name}.slack.com" \
  --form token="${token}" \
  --form only_self_subteams=1 \
  --form flannel_api_ver=4 \
  --form include_min_version_bump_check=1 \
  --form version_ts="${x_version_ts}" \
  --form build_version_ts="${x_version_ts}" \
  --form _x_reason=deferred-data \
  --form _x_sonic=true \
  >meta/$team_name/boot.json 2>log/$team_name/boot.log

  status_code=$(grep "^< HTTP/" "log/$team_name/boot.log" | awk '{ print $3 }')
  if [[ $status_code -ne 200 ]]; then
    # try again
    if [[ $status_code -eq 429 ]]; then
      echo "Rate-limited. Re-trying.."
      sleep 3
    else
      echo "Non-OK code. Re-trying.."
    fi
    sleep 1
  else
    if [[ $(jq .self meta/$team_name/boot.json) == "null" ]]; then
      echo "Invalid json result. Re-trying.."
      if [[ $attempt -gt 3 ]]; then
        echo "Max retries exceeded. Maybe a bad cookie jar at 'cookies/$team_name.jar'? Try deleting it!"
        exit 1
      fi
      (( attempt += 1 ))
    else
      break
    fi
  fi
done

mkdir -p meta/$team_name/users
mkdir -p log/$team_name/meta/users
for i in $(jq . meta/$team_name/boot.json | grep '"U' | tr -d '":,'); do  if [[ "X$i" == "XU"* ]]; then echo "$i"; fi; done | sort | uniq | grep -v Used > meta/$team_name/users.txt
while IFS= read -r u ; do
  echo -n "Loading user profile '$u' .."
  while true ; do
    make-request "https://edgeapi.slack.com/cache/$team_id/users/info" \
    -H 'Content-Type: application/json' \
    --data "{\"token\":\"$token\",\"check_interaction\":true,\"updated_ids\":{\"$u\":0}}" \
    >"meta/$team_name/users/$u.json" 2>"log/$team_name/meta/users/$u.log"

    status_code=$(grep "^< HTTP/" "log/$team_name/meta/users/$u.log" | awk '{ print $3 }')
    if [[ $status_code -ne 200 ]]; then
      # try again
      if [[ $status_code -eq 429 ]]; then
        echo -n s
        sleep 3
      else
        echo -n x
      fi
      sleep 1
    else
      if ! info=$(jq -r '.results[0]|"\(.name) | \(.profile.real_name) | \(.profile.title)"' "meta/$team_name/users/$u.json") ; then
        echo -n j
      else
        echo -n ". $info"
        break
      fi
    fi
  done
  echo
done < "meta/$team_name/users.txt"
