#!/bin/env bash

# share.sh - Shares a file with a link by uploading to a "Gokapi" backend
# Depends on: curl, jq, libsecret

set -e

URL="https://${SHARE_DOMAIN}/api/files/add"

usage() {
    printf "share - Share a file

Usage: share [options] FILE

Options:
    -f <name>\tName of the file that will be uploaded
    -p <passwd>\tPassword
    -d <number>\tAllowed nubmer of downloads
    -e <expiry>\tExpiry in days\n"
}

[ $# -eq 0 ] && usage && exit 1

options=$(getopt "hp:d:e:f:" "$@")
eval set -- "$options"

while true; do
    case $1 in
        -p)
            shift
            PASSWORD="$1"
            ;;
        -d)
            shift
            ALLOWED_DOWNLOADS="$1"
            ;;
        -e)
            shift
            EXPIRY_DAYS="$1"
            ;;
        -f)
            shift
            FILENAME="$1"
            ;;
        -h)
            usage
            exit 0
            ;;
        --)
            shift
            break;;
    esac
    shift
done

[ $# -eq 0 ] && usage && exit 1 || FILE=$1

if [ ! -f "$FILE" ] && [ $FILE != "-" ]; then
    echo "File ${FILE} not found."
    exit 1
fi

APIKEY=$(secret-tool lookup share apikey)
if [ ! "$APIKEY" ]; then
    echo "Please enter your API key for Gokapi"
    secret-tool store --label "API key for share.sh" share apikey
    APIKEY=$(secret-tool lookup share apikey)
fi

read RESULT ID URL HOTLINKURL HOTLINKID < <(echo $(curl -# -X POST \
    --fail \
    -F "file=@${FILE};filename=${FILENAME:-$FILE}" \
    -F "password=${PASSWORD}" \
    -F "allowedDownloads=${ALLOWED_DOWNLOADS:-0}" \
    -F "expiryDays=${EXPIRY_DAYS}" \
    -H "accept: application/json" \
    -H "apikey: ${APIKEY}" \
    -H "Content-Type: multipart/form-data" \
    "${URL}" | jq -r '.Result, .FileInfo.Id, .Url, .HotlinkUrl, .FileInfo.HotlinkId'))

if [ $RESULT != "OK" ]; then
    echo "An error occured when trying to upload the file."
    echo "Result was: $RESULT"
    exit 1
fi

echo "Uploaded url: ${URL}${ID}"
[ ! "$HOTLINKID" ] || echo "Hotlink: ${HOTLINKURL}${HOTLINKID}"