#!/bin/bash
#******************************************************************************
# Copyright 2018 Google
# 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 pulls the latest source files from github into the jwt/crypto
# folder. Run it from it's directory to get the latest files.

# Make temp directory, cd into it.
mkdir tmp
cd tmp

# Clone ecc libraries.
git clone https://github.com/cirvladimir/ecc-light-certificate.git
git clone https://github.com/CSSHL/ESP8266-Arduino-cryptolibs.git

# cd out of tmp.
cd ..

# Copy sources into jwt folder.
cp tmp/ESP8266-Arduino-cryptolibs/sha256/sha256.cpp src/crypto/sha256.cpp
cp tmp/ESP8266-Arduino-cryptolibs/sha256/sha256.h src/crypto/sha256.h
cp tmp/ecc-light-certificate/ecc/curve-params/secp256r1.c src/crypto/secp256r1.cpp
cp tmp/ecc-light-certificate/ecc/ecc.c src/crypto/ecc.cpp
cp tmp/ecc-light-certificate/ecc/ecc.h src/crypto/ecc.h
cp tmp/ecc-light-certificate/ecc/ecdsa.c src/crypto/ecdsa.cpp
cp tmp/ecc-light-certificate/ecc/ecdsa.h src/crypto/ecdsa.h
cp tmp/ecc-light-certificate/ecc/nn.c src/crypto/nn.cpp
cp tmp/ecc-light-certificate/ecc/nn.h src/crypto/nn.h

# Remove unnecessary sha library.
sed -i '/#include "sha2.h"/d' src/crypto/ecdsa.h
# Add some defines since we're not using make.
sed -i '1i#define SHA256_DIGEST_LENGTH 32' src/crypto/ecdsa.h
sed -i '1i#define THIRTYTWO_BIT_PROCESSOR' src/crypto/nn.h
sed -i '1i#define SECP256R1' src/crypto/nn.h

# Change string.h to String.h
for f in src/crypto/ecdsa.cpp src/crypto/nn.cpp src/crypto/secp256r1.cpp src/crypto/sha256.cpp
do
  sed -i 's/#include <string.h>/#include <String.h>/' $f
done

# Add a do not edit comment.
for f in src/crypto/sha256.cpp src/crypto/sha256.h src/crypto/secp256r1.cpp src/crypto/ecc.cpp src/crypto/ecc.h src/crypto/ecdsa.cpp src/crypto/ecdsa.h src/crypto/nn.cpp src/crypto/nn.h
do
  sed -i '1i// AUTOGENERATED, DO NOT EDIT. See CONTRIBUTING.md for instructions.' $f
done

rm -rf tmp
