#!/bin/bash

#First arg should be the local path, second arg should be the remote path.
VERSION="2.0"
#Update onces stable
#APITOKEN=AKCp5cbwXBA2Rarq6WagmFFxQxcxsARGxSq5g1H8NaGm7837KTgwdWPqsp7FdgRa13B7AcpGN
#URL=https://oneartifactorycloud.verizon.com/artifactory

APITOKEN=AKCp5ZmHP8B1dkLtdSh23bMcWHtrWzoB3SfhoCNpEC5e3dKNhiKsn8TPMZQafXzm2qkeXFXE6
URL=https://oneartifactoryprod.verizon.com/artifactory

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

if [ -z $LOGFILE ]; then
LOGFILE="/tmp/${LOCALBASE}.txt"
fi

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

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

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

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..." >> $LOGFILE
echo -e "URL: ${URL}/api/storage/${REMOTEPATH}" >> $LOGFILE
JSON=$(curl --header "X-JFrog-Art-Api: ${APITOKEN}" -X GET "${URL}/api/storage/${REMOTEPATH}" 2>>"${LOGFILE}")
CHECKSUM=$(echo "$JSON" | python3 -c 'import sys, json; print(json.load(sys.stdin)["checksums"]["sha1"])') 2>>"${LOGFILE}"
if [[ -z "$CHECKSUM" ]]; then
exit_with_error "No Checksum found in json: ${JSON}"
fi
echo "Remote checksum ${CHECKSUM}" >> "${LOGFILE}"
OLDCHECKSUM=$(cat "${VERSIONFILE}" 2>/dev/null)
echo "Local checksum ${OLDCHECKSUM}" >> "${LOGFILE}"

#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..." >> "${LOGFILE}"
echo -e "URL: ${URL}/${REMOTEPATH}" >> $LOGFILE
curl --header "X-JFrog-Art-Api: ${APITOKEN}" -f -X GET "$URL/$REMOTEPATH" --output "${NEWFILEPATH}" 2>>"${LOGFILE}"
if [ $? -eq 0 ] && [ -e "${NEWFILEPATH}" ]; then
echo "Finished Downloading, begin unzip" >> "${LOGFILE}"
unzip -q -o "${NEWFILEPATH}" -d "${LOCALDIR}" 2>>"${LOGFILE}"
if [ $? -eq 0 ]; then
echo "Finished unzipping, remove zip" >> "${LOGFILE}"
rm -rf "${NEWFILEPATH}" 2>>"${LOGFILE}"
echo "Writing new checksum to file" >> "${LOGFILE}"
echo "${CHECKSUM}" > "${VERSIONFILE}" 2>>"${LOGFILE}"
echo "Successfully downloaded and unzipped archive." >> "${LOGFILE}"
else
exit_with_error "Error unzipping"
fi
else
exit_with_error "Failed to download"
fi
else
echo "Successful, No New Version" >> "${LOGFILE}"
fi
