#!/bin/bash

# Configuration
USER=""

if [ "$#" -lt 1 ]; then
    echo "Usage: $0 <file> [path]"
    exit 1
fi

GET_SERVER_URL="https://vikingfile.com/api/get-server"
response=$(curl -s "$GET_SERVER_URL")

if command -v jq &> /dev/null; then
    upload_server=$(echo "$response" | jq -r '.server')
else
    upload_server=$(echo "$response" | grep -o '"server":"[^"]*"' | cut -d'"' -f4 | sed 's|\\/|/|g')
fi

if [ -z "$upload_server" ]; then
    echo "Error : Impossible to get upload server"
    exit 1
fi

file="$1"
if [ ! -f "$file" ]; then
    echo "Error : File $file doesn't exist"
    exit 1
fi

if [ "$#" -ge 2 ]; then
    path="$2"
    response=$(curl -X POST "$upload_server" \
        -F "file=@$file" \
        -F "user=$USER" \
        -F "path=$path")
else
    response=$(curl -X POST "$upload_server" \
        -F "file=@$file" \
        -F "user=$USER")
fi

if command -v jq &> /dev/null; then
    url=$(echo "$response" | jq -r '.url')
else
    url=$(echo "$response" | grep -o '"url":"[^"]*"' | cut -d'"' -f4 | sed 's|\\/|/|g')
fi

echo -ne "\033[1A\033[2K"
echo -ne "\033[1A\033[2K"
echo -ne "\033[1A\033[2K"

echo "$url"
