#!/bin/bash

function upload_to_ninjastream () {
    api_ID=$1
    api_SecretID=$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

    upload_server=$(curl -s -X POST "https://api.ninjastream.to/api/file/upload/generate" -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

    hoster_url=$(curl -k -F "file=@\"$filepath\"" -F apiId=$api_ID -F apiSecretId=$api_SecretID $upload_server -H "Content-Type: multipart/form-data") #

    # echo "hoster_url: $hoster_url"  >&2

    hoster_url=$(echo $hoster_url | jq ".result")
    hoster_filename=$(echo $hoster_url | jq ".name")
    hoster_url=$(echo $hoster_url | jq ".id")
    hoster_url=${hoster_url//\"}

    if [ "$hoster_url" != "" ] && [ "$hoster_url" != "null" ]; then
        echo "https://ninjastream.to/watch/$hoster_url"
    else
        echo ""
    fi
}

function ninjastream_check_if_file_is_alive () {
    file_url=$1
    # api_ID=$2
    # api_SecretID=$3
    
    # file_id=${file_url%/*}
    # >&2 echo "File ID: $file_id"
    file_id=${file_url##*/}
    # >&2 echo "File ID: $file_id"
    
    response=$(curl -s -X POST "https://api.ninjastream.to/api/file/get" -F id=$file_id )
    # >&2 echo "Response: $response"
    
    is_alive=$(echo $response | jq ".message")
    # is_alive=$(echo $is_alive | jq ".data")
    # is_alive=$(echo $is_alive | jq "first(.[])")
    # is_alive=$(echo $is_alive | jq ".status")
    
    # >&2 echo $is_alive
    
    if [ "$is_alive" == "\"File not found\"" ]; then
        echo "false"
#   elif [ $is_alive = '500' ]; then
#      echo "false"
    else
        echo "true"
    fi
}
