#!/bin/bash

function upload_to_dropload () {
    api_key=$1
    filepath=$2

    filepath=$( readlink -f "$filepath" )
    # echo "filepath: $filepath" >&2

    filesize=$(stat -c%s "$filepath")
    # echo "filesize: $filesize" >&2

    # echo "https://dropload.io/api/upload/server?key=$api_key" >&2

    upload_server=$(curl -s -X GET "https://dropload.io/api/upload/server?key=$api_key" -H "Content-Type: application/json")
    echo "Upload_URL $upload_server" >&2
    upload_server=$(echo $upload_server | jq ".result")
    upload_server=${upload_server//\"}
    echo "Location: $upload_server"  >&2

    stream_url=$(curl -X POST $upload_server -H "Content-Type: multipart/form-data" -F "file=@\"$filepath\"" -F "key=$api_key")

    echo "stream_url: $stream_url"  >&2

    stream_url=$(echo $stream_url | jq ".files")
    stream_url=$(echo $stream_url | jq "first(.[])")
    stream_url=$(echo $stream_url | jq ".filecode")
    stream_url=${stream_url//\"}
    stream_url="https://dropload.io/${stream_url}.html"

    echo "$stream_url"
}

function dropload_check_if_file_is_alive () {
    api_key=$1
    file_url=$2

    file_id=${file_url%.*}
    # >&2 echo "File ID: $file_id"
    file_id=${file_id##*/}
    # >&2 echo "File ID: $file_id"

    response=$(curl -s -X GET "https://dropload.io/api/file/info?key=$api_key&file_code=$file_id" -H "Content-Type: application/json" )
    # >&2 echo "Response: $response"

    is_alive=$(echo $response | jq ".result")
    is_alive=$(echo $is_alive | jq "first(.[])")
    is_alive=$(echo $is_alive | jq ".status")

    # echo $is_alive

    if [ $is_alive -eq '404' ]; then
        echo "false"
    else
        echo "true"
    fi
}
