#!/bin/bash
set -e

# directory of this script
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "Script directory: $SCRIPT_DIR"

# Check for GITEA_TOKEN_DEPLOY or GITEA_TOKEN
TOKEN="${GITEA_TOKEN_DEPLOY:-${GITEA_TOKEN}}"
[ -z "$TOKEN" ] && { echo "Neither GITEA_TOKEN_DEPLOY nor GITEA_TOKEN environment variable set!" >&2; exit 1; }

"$SCRIPT_DIR/multibuild.sh"
#BUILD_DIR=$SCRIPT_DIR/build

OLD_PWD="$PWD"
cd "$SCRIPT_DIR" || exit 1

# Check for required binaries
REQUIRED_BINARIES=("dropshell.x86_64" "dropshell.aarch64")
for binary in "${REQUIRED_BINARIES[@]}"; do
    if [ ! -f "output/$binary" ]; then
        echo "output/$binary not found!" >&2
        echo "Please run multibuild.sh first." >&2
        exit 1
    fi
done

TAG=$("$SCRIPT_DIR/output/dropshell.x86_64" --version)
[ -z "$TAG" ] && echo "Failed to get version from dropshell.x86_64" >&2 && exit 1

echo "Publishing dropshell version $TAG"

# make sure we've commited.
git add "$SCRIPT_DIR/../" && git commit -m "dropshell release $TAG" && git push


# Find repo info from .git/config
REPO_URL=$(git config --get remote.origin.url)
if [[ ! $REPO_URL =~ gitea ]]; then
    echo "Remote origin is not a Gitea repository: $REPO_URL" >&2
    exit 1
fi

# Extract base URL, owner, and repo
# Example: https://gitea.example.com/username/reponame.git
BASE_URL=$(echo "$REPO_URL" | sed -E 's#(https?://[^/]+)/.*#\1#')
OWNER=$(echo "$REPO_URL" | sed -E 's#.*/([^/]+)/[^/]+(\.git)?$#\1#')
REPO=$(echo "$REPO_URL" | sed -E 's#.*/([^/]+)(\.git)?$#\1#')

API_URL="$BASE_URL/api/v1/repos/$OWNER/$REPO"

# Create release
RELEASE_DATA=$(cat <<EOF
{
  "tag_name": "$TAG",
  "name": "$TAG",
  "body": "dropshell release $TAG",
  "draft": false,
  "prerelease": false
}
EOF
)

# Capture stdout and stderr of the curl command
CURL_OUTPUT=$(curl -X POST "$API_URL/releases" \
    -H "Content-Type: application/json" \
    -H "Authorization: token $TOKEN" \
    -d "$RELEASE_DATA" 2>&1)

# Extract the release ID from the captured output
RELEASE_ID=$(echo "$CURL_OUTPUT" | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)

if [ -z "$RELEASE_ID" ]; then
    echo "Failed to create release on Gitea." >&2
    echo "Release ID returned: $RELEASE_ID" >&2
    echo "Curl Output/Error:" >&2
    echo "$CURL_OUTPUT" >&2
    exit 1
fi

# Function to find file in specified locations
find_file() {
    local filename="$1"
    shift # remove filename from args
    local locations=("$@") # grab the rest of the args as locations

    for loc in "${locations[@]}"; do
        if [ -f "$loc/$filename" ]; then
            echo "$loc/$filename"
            return 0 # Found the file, return success
        fi
    done
    echo "" # Return empty string if not found
    return 1
}

# Upload binaries and install.sh
for FILE in dropshell.x86_64 dropshell.aarch64 install.sh server_autosetup.sh; do
    # Pass the locations directly to the find_file function
    filetoupload=$(find_file "$FILE" "output" "../" ".")
    if [ -z "$filetoupload" ]; then
        echo "File $FILE not found in expected locations!" >&2
        continue
    fi

    # Auto-detect content type
    ctype=$(file --mime-type -b "$filetoupload")

    curl -X POST "$API_URL/releases/$RELEASE_ID/assets?name=$FILE" \
        -H "Content-Type: $ctype" \
        -H "Authorization: token $TOKEN" \
        --data-binary @"$filetoupload"
    echo "Uploaded $FILE to release $TAG as $ctype."
done

echo "Published dropshell version $TAG to $REPO_URL (tag $TAG) with binaries."

cd "$OLD_PWD" || exit 1