#!/bin/bash

url=$1
location=$2
user=$3
password=$4
token=$5
install_cli=$6  # not used
sha=$7 # not used
name=$8

if [[ $location != "None" ]];then
  cd $location
fi

# Isolate the archive in a directory to have only one file inside it
archive_dir="$(dbus-uuidgen)"
mkdir "./$archive_dir"
cd "./$archive_dir"

options="-O -J -L"
if [[ "$token" != "None" ]]; then
  curl -H "Authorization: Bearer $token" $options $url
else
  if [[ $user != "None" ]] && [[ $password != "None" ]];then
    curl $options -u $user:$password $url
  else
    if [[ $user != "None" ]] && [[ $password == "None" ]];then
      curl $options -u $user $url
    else
      curl $options $url
    fi
  fi
fi

archive=`ls`
python3 -c "import shutil; shutil.unpack_archive('${archive}'); print('Archive uncompressed')"
if [[ $? -ne 0 ]]; then
  exit 1
fi

rm $archive

package=`ls`

if [[ "$name" != "None" ]] && [[ $name != $package ]]; then
  mv $package $name
fi

cd ..
mv -f $archive_dir/* .
rm -rf $archive_dir

