#!/bin/sh

# Usage: curl -fsSL https://deploy.astrid.ovh | bash -s -- <directory> --id <id> --api-key <key>

set -e

API_URL="https://deploy.astrid.ovh"
DIR_TO_DEPLOY=""
PREFIX="${RAILWAY_GIT_COMMIT_SHA:-$SOURCE_COMMIT}"
API_KEY=""

usage() {
    echo "Usage: $0 <directory> --id <id> --api-key <key>"
    exit 1
}

while [ $# -gt 0 ]; do
    case "$1" in
        --id)
            PREFIX="$2"
            shift 2
            ;;
        --api-key)
            API_KEY="$2"
            shift 2
            ;;
        -*)
            echo "Unknown option: $1"
            usage
            ;;
        *)
            if [ -z "$DIR_TO_DEPLOY" ]; then
                DIR_TO_DEPLOY="$1"
                shift
            else
                echo "Unexpected argument: $1"
                usage
            fi
            ;;
    esac
done

DIR_TO_DEPLOY="${DIR_TO_DEPLOY:-.}"

if [ -z "$PREFIX" ]; then
    echo "Error: Deployment ID not found. Use --id or set RAILWAY_GIT_COMMIT_SHA/SOURCE_COMMIT"
    exit 1
fi

if [ -z "$API_KEY" ]; then
    echo "Error: --api-key is required"
    exit 1
fi

if [ ! -d "$DIR_TO_DEPLOY" ]; then
    echo "Error: Directory '$DIR_TO_DEPLOY' does not exist."
    exit 1
fi

if command -v apk >/dev/null 2>&1; then
    apk add --quiet --no-cache curl tar gzip
elif command -v apt-get >/dev/null 2>&1; then
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -qq && apt-get install -y -qq curl tar gzip
fi

TARBALL_NAME="deploy-$(date +%s).tar.gz"

cd "$DIR_TO_DEPLOY" && tar -czf "../$TARBALL_NAME" . && cd ..

HTTP_RESPONSE=$(curl -s -w "\n%{http_code}" \
    -X POST "$API_URL/deploy?prefix=$PREFIX" \
    -H "Authorization: Bearer $API_KEY" \
    -F "file=@$TARBALL_NAME")

HTTP_CODE=$(echo "$HTTP_RESPONSE" | tail -n 1)
HTTP_BODY=$(echo "$HTTP_RESPONSE" | sed '$d')

rm "$TARBALL_NAME"

if [ "$HTTP_CODE" -eq 200 ]; then
    exit 0
else
    echo "Failed: $HTTP_CODE"
    echo "$HTTP_BODY"
    exit 1
fi
