#!/bin/bash -e

#  upload_framework.sh
#
#  Uploads an iOS framework to Artificatory given the local path as the first argument and the remote project name in Verizon OneArtifactory for the second argument.
#
#  An API key from Artifcatory is required in the api_key.private file before uploading.
#
#  The script will replace [VER] in the provided remote path with the version found in the framework bundle.
#
#  Copied from Hedden, Kyle Matthew on 3/2/18.
#  Copyright © 2018 Verizon. All rights reserved.

URL=$1
LOCALPATH=$2
REMOTEPATH=$3

if [ -z $URL ]; then
    echo "The artifactory instance url must be specified as the first argument!"
    exit 1
fi

echo ">>> UPLOAD START <<<"
echo "Local path: ${LOCALPATH}"
echo "Remote path: ${REMOTEPATH}"

cat "${LOCALPATH}/Info.plist"

LOCALBASE=$(basename "${LOCALPATH}")
LOCALDIR=$(dirname "${LOCALPATH}")

# Grab the framework version from the bundled Info.plist.
FRAMEWORKVER=$(/usr/libexec/plistbuddy -c "Print :CFBundleShortVersionString" "${LOCALPATH}/Info.plist")
echo -e "\nFramework version: \t${FRAMEWORKVER}"

# Replace the [VER] placeholders with the found version.
REMOTEPATH="${REMOTEPATH//\[VER\]/$FRAMEWORKVER}"
echo -e "Resolved path: \t\t${REMOTEPATH}"

if [ -z $ARTIFACTORY_APIKEY ]; then
    # Read the API key from a private file.
    read -r APIKEY < "api_key.private"
else
    APIKEY=$ARTIFACTORY_APIKEY
fi

if [ -z $APIKEY ]; then
    read -p "Artifactory API Key:" APIKEY
    echo $APIKEY >> api_key.private
fi

echo -e "API Key: \t\t${APIKEY}"

# Zip the framework & DSYM for uploading.
pushd $LOCALDIR
echo -e "---------\nZipping: \t\t${LOCALBASE}.zip"
zip -r -X "${LOCALBASE}.zip" $LOCALBASE
# Generate framework's SHA-1 checksum.
CHECKSUM=$(shasum -a 1 "${LOCALBASE}.zip" | cut -d " " -f 1)
echo -e "SHA-1 Checksum: \t${CHECKSUM}"
if [ -e ${LOCALBASE}.dSYM ]; then
    echo -e "---------\nZipping: \t\t${LOCALBASE}.dSYM.zip"
    zip -r -X "${LOCALBASE}.dSYM.zip" $LOCALBASE.dSYM
    # Generate its SHA-1 checksum for dsym.
    DSYM_CHECKSUM=$(shasum -a 1 "${LOCALBASE}.dSYM.zip" | cut -d " " -f 1)
    echo -e "SHA-1 Checksum: \t${DSYM_CHECKSUM}"
fi
popd
mv ${LOCALPATH}.zip .
if [ -e ${LOCALPATH}.dSYM.zip ]; then
    mv ${LOCALPATH}.dSYM.zip .
fi

# Upload framework to Artifactory.
echo -e "---------\nUploading to: \t\t${URL}/${REMOTEPATH}.zip"
curl --header "X-JFrog-Art-Api: ${APIKEY}" --header "X-Checksum-Sha1: ${CHECKSUM}" -X PUT "${URL}/${REMOTEPATH}.zip" -T "${LOCALBASE}.zip"

# Cleanup.
rm "${LOCALBASE}.zip"

if [ -e ${LOCALBASE}.dSYM.zip ]; then
    # Upload dsym Artifactory.
    echo -e "---------\nUploading to: \t\t${URL}/${REMOTEPATH}.dSYM.zip"
    curl --header "X-JFrog-Art-Api: ${APIKEY}" --header "X-Checksum-Sha1: ${DSYM_CHECKSUM}" -X PUT "${URL}/${REMOTEPATH}.dSYM.zip" -T "${LOCALBASE}.dSYM.zip"
    # Cleanup dsym.
    rm ${LOCALBASE}.dSYM.zip
fi

echo -e "\n\n<<< UPLOAD COMPLETE >>>\n\n"
