xref: /aosp_15_r20/external/pigweed/pw_env_setup/get_pw_env_setup.sh (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1#!/bin/sh
2# Copyright 2020 The Pigweed Authors
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may not
5# use this file except in compliance with the License. You may obtain a copy of
6# the License at
7#
8#     https://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations under
14# the License.
15
16if [ -z "$PW_ENVIRONMENT_ROOT" ]; then
17  PW_ENVIRONMENT_ROOT="$PW_ROOT/environment"
18fi
19PREFIX="$PW_ENVIRONMENT_ROOT/bootstrap"
20mkdir -p "$PREFIX"
21
22set -o errexit
23
24# Update the mtimes on the most recent pw_env_setup executables.
25for HASH in $(git --git-dir="$PW_ROOT/.git" --no-pager log --max-count=5 --format=format:%H); do
26  if [ -f "$PREFIX/$HASH" ]; then
27    touch "$PREFIX/$HASH" &> /dev/null
28  fi
29done
30
31# Delete any files with an (apparent) age greater than 5 days. This will never
32# include the 5 most recent pw_env_setup executables, but if there's been no
33# bootstrap call in less than 5 days this could delete all versions of
34# pw_env_setup. This is acceptable because it's very unlikely there have been
35# no commits in a 5 day period, and if there really have been no commits this
36# will just re-download that executable in a few lines.
37find "$PREFIX" -mtime +5 -exec rm {} \;
38
39OS=$(uname -s | tr '[:upper:]' '[:lower:]')
40if [ "$OS" = "darwin" ]; then
41  OS=mac
42fi
43
44ARCH=$(uname -m | tr '[:upper:]' '[:lower:]')
45if [ "$ARCH" = "x86_64" ]; then
46  ARCH="amd64"
47fi
48
49# Support `mac-arm64` through Rosetta until `mac-arm64` binaries are ready
50if [[ "$OS" = "mac" ] && \
51    [ "$ARCH" = "arm64" ] && \
52    [ -n "$PW_BOOTSTRAP_USE_ROSETTA" ]]
53then
54  ARCH="amd64"
55fi
56
57for HASH in $(git --git-dir="$PW_ROOT/.git" --no-pager log --max-count=10 --format=format:%H); do
58  URL="https://storage.googleapis.com/pigweed-envsetup/$OS-$ARCH"
59  URL="$URL/$HASH/pw_env_setup"
60  FILEPATH="$PREFIX/$HASH"
61
62  # First try curl.
63  if [ ! -f "$FILEPATH" ]; then
64    curl -o "$FILEPATH" "$URL" &> /dev/null
65  fi
66
67  # If curl fails try wget.
68  if [ ! -f "$FILEPATH" ]; then
69    wget -O "$FILEPATH" "$URL" &> /dev/null
70  fi
71
72  # If either curl or wget succeeded mark the file executable, print it, and
73  # exit. If the file appears to be a text file then it doesn't exist in GCS
74  # and we'll try the next one.
75  TEXT=$(file --mime "$FILEPATH" | grep text)
76  if [ -n "$TEXT" ]; then
77    rm "$FILEPATH"
78    continue
79  fi
80
81  if [ -f "$FILEPATH" ]; then
82    chmod a+x "$FILEPATH"
83    echo "$FILEPATH"
84    exit 0
85  fi
86done
87
88exit -1
89