#!/bin/bash
# Upload build artifact to Hetzner Storage Box
# Usage: upload-release.sh <version> <platform> <file>
set -euo pipefail

VERSION=${1:-$(date +%Y%m%d_%H%M)}
PLATFORM=${2:-android}
FILE=${3:-}

if [ -z "${FILE:-}" ]; then
    echo "Usage: upload-release.sh <version> <platform> <file>"
    echo "  version:  e.g. v1.0.0 or 20260329_1400"
    echo "  platform: android|ios|web"
    echo "  file:     path to build artifact"
    exit 1
fi

if [ ! -f "$FILE" ]; then
    echo "ERROR: File not found: $FILE"
    exit 1
fi

REMOTE="u458763-sub3@u458763.your-storagebox.de"
PORT=23
EXT=$(echo "$FILE" | rev | cut -d. -f1 | rev)
REMOTE_NAME="task-team-${VERSION}.${EXT}"

echo "[$(date +%H:%M:%S)] Uploading $FILE to releases/$PLATFORM/$REMOTE_NAME..."

# Try direct upload first
if scp -P $PORT -o ConnectTimeout=10 -o BatchMode=yes "$FILE" "$REMOTE:releases/$PLATFORM/$REMOTE_NAME" 2>/dev/null; then
    echo "[$(date +%H:%M:%S)] OK: Uploaded to releases/$PLATFORM/$REMOTE_NAME"
    exit 0
fi

echo "[$(date +%H:%M:%S)] Direct upload failed, trying via mngmt relay..."
# Fallback: relay through mngmt (46.62.219.52)
TEMP_FILE="/tmp/release-upload-$$.tmp"
if scp -P 22770 -o ConnectTimeout=10 "$FILE" root@46.62.219.52:$TEMP_FILE 2>/dev/null; then
    ssh -p 22770 -o ConnectTimeout=10 root@46.62.219.52 "scp -P 23 -o BatchMode=yes $TEMP_FILE $REMOTE:releases/$PLATFORM/$REMOTE_NAME 2>/dev/null; rm -f $TEMP_FILE"
    if [ $? -eq 0 ]; then
        echo "[$(date +%H:%M:%S)] OK: Uploaded via mngmt relay"
        exit 0
    fi
fi

# Last resort: save locally
LOCAL_ARCHIVE="/opt/task-team/backups/releases"
mkdir -p "$LOCAL_ARCHIVE/$PLATFORM"
cp "$FILE" "$LOCAL_ARCHIVE/$PLATFORM/$REMOTE_NAME"
echo "[$(date +%H:%M:%S)] WARN: Storage box unreachable. Saved locally: $LOCAL_ARCHIVE/$PLATFORM/$REMOTE_NAME"
exit 1
