Merge "Migrate to stable/newton"
[apex.git] / build / cache.sh
1 #!/bin/sh
2 ##############################################################################
3 # Copyright (c) 2016 Red Hat Inc.
4 # Dan Radez <dradez@redhat.com>
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10
11 CACHE_DIR="$(pwd)/cache"
12
13 # Make sure the cache dir exists
14 function cache_dir {
15     if [ ! -d $CACHE_DIR/ ]; then mkdir $CACHE_DIR/; fi
16     if [ ! -f $CACHE_DIR/.cache ]; then touch $CACHE_DIR/.cache; fi
17     echo "Cache Dir: $CACHE_DIR"
18 }
19
20 function cache_git_tar {
21     echo "cache_git_tar git ls-remote"
22 }
23
24 # $1 = download url
25 # $2 = filename to write to
26 function curl_file {
27     if [ -f $CACHE_DIR/$2 ]; then
28     echo "Removing stale $2"
29         rm -f $CACHE_DIR/$2
30     fi
31     echo "Downloading $1"
32     echo "Cache download location: $CACHE_DIR/$2"
33     until curl -C- -L -o $CACHE_DIR/$2 $1  || (( count++ >= 20 )); do
34         echo -n '' #do nothing, we just want to loop
35     done
36     sed -i "/$2/d" $CACHE_DIR/.cache
37     echo "$(md5sum $CACHE_DIR/$2) $2" >> $CACHE_DIR/.cache
38 }
39
40 # $1 =  download url
41 # $2 =  remote md5
42 function populate_cache {
43     local my_md5
44     cache_dir
45
46     # get the file name
47     filename="${1##*/}"
48     # copy passed in md5
49     remote_md5=$2
50
51     # check if the cache file exists
52     # and if it has an md5 compare that
53     echo "Checking cache file exists: ${filename}"
54     if [ ! -f $CACHE_DIR/${filename} ]; then
55         echo "Cache file: ${CACHE_DIR}/${filename} missing...will download..."
56         curl_file $1 $filename
57     else
58         echo "Cache file exists...comparing MD5 checksum"
59         if [ -z $remote_md5 ]; then
60             remote_md5="$(curl -sf -L ${1}.md5 | awk {'print $1'})"
61         fi
62         if [ -z "$remote_md5" ]; then
63             echo "Got empty MD5 from remote for $filename, skipping MD5 check"
64             curl_file $1 $filename
65         else
66             my_md5=$(grep ${filename} $CACHE_DIR/.cache | awk {'print $1'})
67             if [ "$remote_md5" != "$my_md5" ]; then
68                 echo "MD5 mismatch, cache file MD5 is ${my_md5}"
69                 echo "Downloading $filename"
70                 curl_file $1 $filename
71             else
72               echo "Will use cache for ${filename}"
73             fi
74         fi
75     fi
76 }
77
78 # $1 = filename to get from cache
79 function get_cached_file {
80   cp -f $CACHE_DIR/$1 .
81 }