#!/bin/bash

# This script will download the requested zip and store it in
# "zips/" for install step which will put it in the binary package.

set -e

SCRIPT_PATH=$(dirname $0)

source $SCRIPT_PATH/_components_to_package.sh
source $SCRIPT_PATH/_common_functions.sh

echo $1
if [[ "$1" =~ .*/.* ]]; then
  LOCAL_ZIP_DIR="$1"
else
  LOCAL_ZIP_DIR="../google-android-installers-zips"
fi

shift

for version in "$@"; do

  echo "Processing $version "

  ZIPFILE="$(get_zip_filename "$version")"

  if [ -z "$ZIPFILE" ]; then
    echo "Problem with $version. Probably incorrect value".
    exit 1
  fi

  echo "Zipfile: $ZIPFILE"

  if [ ! -e "$PACKAGE_ZIP_DIR/$ZIPFILE" ]; then
    mkdir -p zips
    if [ -e "$LOCAL_ZIP_DIR/$ZIPFILE" ]; then
      cp --reflink=auto -af "$LOCAL_ZIP_DIR/$ZIPFILE" "$PACKAGE_ZIP_DIR/"
    else
      (cd "$PACKAGE_ZIP_DIR" && wget -nc "https://dl.google.com/android/repository/$ZIPFILE")
      if [ -d "$LOCAL_ZIP_DIR" ]; then
        cp -a "$PACKAGE_ZIP_DIR/$ZIPFILE" "$LOCAL_ZIP_DIR/"
      fi
    fi
  fi

done
echo "Finished adding zip files"
