#!/bin/bash -e

#  upload_framework.sh
#
#  Downloads an iOS framework from Artificatory.
#
#  An API key from Artifcatory is required in the api_key.private file before uploading.
#

URL=$1
LOCALPATH="${2}"
REMOTEPATH="${3}"
LOGFILE=$3
LOCALDIR=$(dirname "${LOCALPATH}")
LOCALBASE=$(basename "${LOCALPATH}")
NEWFILEPATH="${LOCALDIR}"/$(basename "${REMOTEPATH}")
VERSIONFILE=$LOCALDIR/Checksums/"${LOCALBASE}".txt

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

#first argument is error message.
exit_with_error () {
echo "Error: $1"
if [ -f "${NEWFILEPATH}" ]; then
    rm -rf "${NEWFILEPATH}" 2
fi
exit 1
}

echo "----------------------------------------------------------"
echo "Logs for ${LOCALBASE}"

echo -e "Local Target: ${LOCALPATH}"
echo -e "Remote Source: ${REMOTEPATH}"

if [ -z "$LOCALPATH" ]; then
    exit_with_error "Missing local path argument"
fi

if [ -z "$REMOTEPATH" ]; then
    exit_with_error "Missing filename path argument"
fi

#get local and remote checksums for comparison
echo -e "Getting checksums..."
echo -e "URL: ${URL}/api/storage/${REMOTEPATH}"
JSON=$(curl --header "X-JFrog-Art-Api: ${ARTIFACTORY_APIKEY}" -X GET "${URL}/api/storage/${REMOTEPATH}")
CHECKSUM=$(echo "$JSON" | python -c 'import sys, json; print json.load(sys.stdin)["checksums"]["sha1"]')
if [[ -z "$CHECKSUM" ]]; then
    exit_with_error "No Checksum found in json: ${JSON}"
fi
echo "Remote checksum ${CHECKSUM}"
if [[ -f "${VERSIONFILE}" ]]; then
    OLDCHECKSUM=$(cat "${VERSIONFILE}")
else
    OLDCHECKSUM="none"
    mkdir -p $(dirname ${VERSIONFILE}) && touch "$VERSIONFILE"
fi
echo "Local checksum ${OLDCHECKSUM}"

#get new framework if no original framework, no local checksum, or remote checksum is different from local.
if [ ! -e "${LOCALPATH}" ] || [ -z "$OLDCHECKSUM" ] || [ "$CHECKSUM" != "$OLDCHECKSUM" ]; then
    echo "Downloading..."
    echo -e "URL: ${URL}/${REMOTEPATH}"
    curl --header "X-JFrog-Art-Api: ${ARTIFACTORY_APIKEY}" -f -X GET "$URL/$REMOTEPATH" --output "${NEWFILEPATH}"
    if [ $? -eq 0 ] && [ -e "${NEWFILEPATH}" ]; then
        echo "Finished Downloading, begin unzip"
        unzip -q -o "${NEWFILEPATH}" -d "${LOCALDIR}"
        if [ $? -eq 0 ]; then
            echo "Finished unzipping, remove zip"
            rm -rf "${NEWFILEPATH}"
            echo "Writing new checksum to file"
            echo "${CHECKSUM}" > "${VERSIONFILE}"
            echo "Successfully downloaded and unzipped archive."
        else
            exit_with_error "Error unzipping"
        fi
    else
        exit_with_error "Failed to download"
    fi
else
    echo "Successful, No New Version"
fi
