#!/bin/bash

function upload_to_streamtape () {
    api_user=$1
    api_key=$2
    filepath=$3

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

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

    filesha256=$( sha256sum "$filepath")
    filesha256=${filesha256%% *}

    echo "filesha256 $filesha256" >&2
    echo "https://api.streamtape.com/file/ul?login=$api_user&key=$api_key&sha256=$filesha256" >&2

    upload_server=$(curl -s -X GET "https://api.streamtape.com/file/ul?login=$api_user&key=$api_key&sha256=$filesha256" -H "Content-Type: application/json")
    echo "Upload_URL $upload_server" >&2
    upload_server=$(echo $upload_server | jq ".result")
    upload_server=$(echo $upload_server | jq ".url")
    upload_server=${upload_server//\"}
    echo "Location: $upload_server"  >&2

    streamtape_url=$(curl -X POST $upload_server -H "Content-Type: multipart/form-data" -F "file1=@\"$filepath\"")

    streamtape_url=$(echo $streamtape_url | jq ".result")
    streamtape_url=$(echo $streamtape_url | jq ".url")
    streamtape_url=${streamtape_url//\"}

    echo "$streamtape_url"
}

function streamtape_check_if_file_is_alive () {
    file_url=$1

    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://api.streamtape.com/file/info?file=$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
}
