#!/bin/bash
source "$ROOT_PATH"/scripts/common.sh
set -eo pipefail

# Function to handle errors
handle_error() {
    echo_red_bg "Error: $1"
    exit 1
}


file_type=$(file -b "lambda.zip")

if [[ "$file_type" == *"Zip archive data"* ]]; then
    echo "File is a ZIP file. continue.."
elif [[ "$file_type" == *"gzip compressed data"* ]]; then
    echo "File is a GZIP file. changing to zip for aws lambda"
    tar zxvf lambda.zip || handle_error "Failed to untar the gzip file."
    if [ -f "lambda.zip" ]; then
        echo "Removing existing ZIP file to allow overwriting..."
        rm -f "lambda.zip"
    fi
    (cd package/dist/ && zip -r - .) >lambda.zip || handle_error "Failed to zip the content of package dir."
    echo "create a new lambda.zip"
else
    echo "File is neither a ZIP nor a GZIP file."
    handle_error "Failed to define file type (can be only zip or gzip)"
fi
