#!/usr/bin/env bash
set -e

zip="${1}"

if [ -z "${zip}" ]; then
	echo "Usage: $0 <zip-file>"
	echo
	echo "Ensure the zip file matches the cosmovisor expected formatting"
	echo
	exit 1
fi

# Colorize the ouput.
red='\e[0;31m'
green='\e[0;32m'
lite_blue='\e[1;34m'
lite_red='\e[1;31m'
yellow='\e[1;33m'
off='\e[0m'

# Fix the zip name to prevent overwriting.
oldZip="$(basename "${zip}")"
zipDir="$(dirname "${zip}")"
newZip="$(basename "${oldZip}" .zip)-fixed.zip"
curDir="$(pwd)"

# Does the zip already match the format needed? (ie: bin/ dir with provenanced binary in it)
if unzip -l "${zip}" bin/provenanced > /dev/null; then
	echo -e "${green}Success!${off} - Binary already located in bin/ dir within zip"
	exit 0
fi

# Create the proper layout.
myTmpDir=$(mktemp -d 2>/dev/null || mktemp -d -t 'mytmpdir')

# Unpack into the new layout.
echo -e "${lite_blue}Extracting ${yellow}${zip}${off}"
mkdir -p "${myTmpDir}/bin"
unzip "${zip}" -d "${myTmpDir}/bin/"
cd "${myTmpDir}" || exit

# Re-zip the new layout files.
echo -e "${lite_blue}Creating ${yellow}${zipDir}/${newZip}${off}"
zip "${zipDir}/${newZip}" -r bin/
cd "${curDir}"

echo -e "${lite_blue}Overwriting ${yellow}${zip}${off}"
mv -v "${zipDir}/${newZip}" "${zipDir}/${oldZip}"
rm -rf "${myTmpDir}"

echo -e "${green}Success!${off}"
