#!/bin/bash

gdownload() {
  URL=$1
  OUTFILE=$2
  COOKIES="/tmp/${RANDOM}.cookie"

  if [ -z "$URL" -o -z "$OUTFILE" ]; then
    return 1
  fi

  # Get cookie with skip verification code
  curl -sc "$COOKIES" "$URL" &> /dev/null

  # Extract skip verification code from cookie
  CODE="$(awk '/_warning_/ {print $NF}' $COOKIES)"

  echo "Code: $CODE"

  # Download the actual file
  echo "Using link: " "$URL&confirm=$CODE"
  curl -Lb "$COOKIES" "$URL&confirm=$CODE" -o "$OUTFILE"

  # Cleanup cookie file
  rm "$COOKIES"

  return $?
}

install() {
  DLFILE="/tmp/tensorflow-2.7.0-cp39-none-linux_aarch64.whl"

  # Try to download the wheel file from google drive
  if gdownload "https://drive.google.com/uc?export=download&id=1D3R7bzkuFdY_gGTkSmnF9IbRNlj9wssB" "$DLFILE"; then
    # Install the downloaded wheel
    pip3 install "$DLFILE"

    # Save the pip3 install return code (0 => success)
    PIPRC="$?"

    # Cleanup the downloaded wheel
    rm "$DLFILE"

    return $PIPRC
  fi

  return 1
}

install