#!/bin/bash
#
# This file is part of GetTor, a Tor Browser distribution system.
#
# :authors: hiro <hiro@torproject.org>
#           see also AUTHORS file
#
# :copyright:   (c) 2008-2019, The Tor Project, Inc.
#
# :license: This is Free Software. See LICENSE for license information.

cd ~/releases
git checkout master
git branch -D torbrowser-releases
git push github --delete torbrowser-releases

git fetch --all --prune

git add .
git commit -am 'Create release branch'
git checkout -b torbrowser-releases
git push -f --follow-tags origin torbrowser-releases
git push -f --follow-tags github torbrowser-releases


for row in $(
    curl -s 'https://aus1.torproject.org/torbrowser/update_3/release/downloads.json' |
    jq -r '.downloads'
  ); do
    r=$(
      echo ${row} |
      egrep -o 'https?://[^ ]+' |
      tr -d '",'
    );
    if [[ $r = *[!\ ]* ]]; then
      git fetch --all
      wget $r
      git add .
      git commit -m '[dist ci] commit from CI runner - update with new torbrowser downloads'
      diffs=$(git diff origin/torbrowser-releases)
      if [ -z "$diffs" ]; then
          echo "No new releases"
      else
          git push -f --follow-tags origin torbrowser-releases
      fi
      diffs=$(git diff github/torbrowser-releases)
      if [ -z "$diffs" ]; then
          echo "No new releases"
      else
          git push -f --follow-tags github torbrowser-releases
      fi
    fi;
done

rclone delete gdrive:releases

for f in $(ls); do
  # Update Google Drive
  rclone copy $f gdrive:releases
  # Update Internet Archive
  ia upload ${f} $f --remote-name=$f --metadata="title:${f}" --metadata="mediatype:software" --metadata="collection:open_source_software"
done
