#!/bin/sh

read_var() {
    if [ -z "$1" ]; then
        echo "environment variable name is required"
        return
    fi

    local ENV_FILE='.env'
    if [ ! -z "$2" ]; then
        ENV_FILE="$2"
    fi

    local VAR=$(grep $1 "$ENV_FILE" | xargs)
    IFS="=" read -ra VAR <<<"$VAR"
    echo ${VAR[1]}
}

autoFolder=$(read_var AUTO_UPDATE_FOLDER)
product=$(read_var APP_PRODUCT)

updaterFilename="laraupdater.json"

version=$(<public/version.txt)

filename="$product-auto-$version"

autoUpdateFolder="$autoFolder/"$product

logs=()
echo "Enter Change Log $version (Write END to end the multi-line)"

while read log; do

    if [ "$log" == "END" ]; then
        break
    fi
    logs+=("<li>"$log"</li>")

done

echo "$updaterFilename file"
now="$(date +'%Y-%m-%d')"

echo "{
    \"version\": \"$version\",
    \"archive\": \"$filename.zip\",
    \"description\": \"<ul>${logs[@]}</ul>\",
    \"release_date\": \"${now}\"
}"

echo "{
    \"version\": \"$version\",
    \"archive\": \"$filename.zip\",
    \"description\": \"<ul>${logs[@]}</ul>\",
    \"release_date\": \"${now}\"
}" >$updaterFilename

echo "Deleting old $filename.zip file"
rm -rf "$autoUpdateFolder/$filename".zip

echo "-> Zipping..."

# shellcheck disable=SC2164
cd "$autoUpdateFolder" && zip -r "$filename".zip . && cd -

while true; do
    # shellcheck disable=SC2039
    read -p "-> Upload $filename.zip and $updaterFilename to S3 server? (y/n)" yn
    case $yn in
    [Yy]*)
        echo "-> Uploading $filename.zip to froiden-update-hub S3 Securely"
        aws s3 cp "$autoUpdateFolder/$filename".zip s3://froiden-update-hub"/$product/"

        echo "-> Uploading $updaterFilename to froiden-update-hub bucket S3 publicly"
        aws s3 cp $updaterFilename s3://froiden-update-hub"/$product/" --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers

        break
        ;;
    [Nn]*) break ;;
    *) echo "Please answer yes or no." ;;
    esac
done

echo "---------------------------------------------------------"
echo "-> UPLOADING COMPLETED $filename.zip and $updaterFilename"
echo "---------------------------------------------------------"
