#!/usr/bin/env bash

# Microsoft Azure Linux Agent
#
# Copyright 2018 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

#
# This script is used to prepare a tarball containing Pypy with the assert-py module pre-installed.
# It needs to be run on x64 and arm64 VMs and the resulting tarballs need to be uploaded to storage,
# from where they are downloaded and installed to the test VMs (see wiki for detail).
#

set -euo pipefail

cd /tmp
rm -rf pypy3.7-*

arch=$(uname -m)
printf "Preparing Pypy for architecture %s...\n" $arch

printf "\n*** Downloading Pypy...\n"
if [[ $arch == "aarch64" ]]; then
  tarball="pypy3.7-arm64.tar.bz2"
  wget https://downloads.python.org/pypy/pypy3.7-v7.3.5-aarch64.tar.bz2 -O $tarball
else
  tarball="pypy3.7-x64.tar.bz2"
  wget https://downloads.python.org/pypy/pypy3.7-v7.3.5-linux64.tar.bz2 -O $tarball
fi

printf "\n*** Installing assertpy...\n"
tar xf $tarball
./pypy3.7-v7.3.5-*/bin/pypy -m ensurepip
./pypy3.7-v7.3.5-*/bin/pypy -mpip install assertpy

printf "\n*** Creating new tarball for Pypy...\n"
# remove the cache files created when Pypy, and set the owner to 0/0, in order to match the original tarball
find pypy3.7-v7.3.5-* -name '*.pyc' -exec rm {} \;
mv -v $tarball "$tarball.original"
tar cf $tarball --bzip2 --owner 0:0 --group 0:0 pypy3.7-v7.3.5-*
rm -rf pypy3.7-v7.3.5-*

printf "\nPypy is ready at %s\n"  "$(pwd)/$tarball"

