#!/bin/bash -eux

curl -Ls https://apps.nextcloud.com/api/v1/platform/${VERSION}/apps.json > /tmp/apps.json

function download_link() {
  cat /tmp/apps.json | jq '.[] | select(.id == "'$1'") | .releases | map(select(.version|test("beta|rc|RC|build")|not)) | sort_by(.version | split(".") | map(tonumber))[-1] | .download'
}

links=`cat ./install-list | xargs -I@ bash -c "$(declare -f download_link) ; download_link @ ; " | tr -d '"'`

mkdir -p apps
cd apps

for link in $links; do
  echo "downloading $link..."
  curl -Ls $link | tar xz
done

# Temp fix for https://github.com/owncloud/music/issues/818
cd music && chmod -R 755 dist/
