#!/bin/sh
# script for downloading videos/audios from sites...
#shellcheck disable=SC2317,SC2329

info() {
	printf "\033[1;36m%s\033[0m\n" "$2" "$3" "$1"
}

notify_droid() {
	info "$1"
	termux-notification -c "$1"
}

notify_linux() {
	info "$1"
	notify-send -e -i "$3" -h "string:x-canonical-private-synchronous:${0##*/}" -t "${2:-5000}" "$1" "$4"
}

compress() {
	duration=$(ffprobe -hide_banner -i "$1" 2>&1 | sed -nE 's|.*Duration: ([^,]*).*|\1|p')
	i=20

	while :; do
		ffmpeg -loglevel error -i "$1" -c:v libx264 -c:a copy -crf "$i" "$process_file" -y -progress - | while read -r line; do
			complete=$(printf "%s\n" "$line" | sed -nE 's|out_time=(.*)|\1|p')
			size=$(du -m "$process_file" | cut -f1)
			[ -n "$complete" ] && notify_$os "Compressing File under $target_size_mb MB Using Quality Preset : $i.." "700" "ffmpeg" "$complete / $duration ($size MB)"
			[ "$size" -gt "$target_size_mb" ] && killall -s KILL ffmpeg && break
		done
		[ "$(du -m "$process_file" | cut -f1)" -lt "$target_size_mb" ] && break
		: $((i += 1))
	done
	notify_$os "File Successfully compressed with Quality Preset : $i" "1000" "ffmpeg"
	[ -f "$process_file" ] && filepath=$process_file
}

send_matrix_msg() {
	# file existance
	[ -f "$1" ] || return 1

	# upload file and get URI
	file_uri=$(curl "$MX_URL/_matrix/media/v3/upload?filename=$filename" -sX POST -H 'Content-Type: application/octet-stream' -H "Authorization: Bearer $MX_TOKEN" -T "$1" | sed -nE 's|.*"content_uri":"([^"]*)".*|\1|p')

	#extract specific data from metadata
	filename="${1##*/}"
	metadata=$(ffprobe -v error -select_streams v:0 -show_entries stream=width,height -show_format "$1")
	width=$(printf '%s' "$metadata" | sed -nE 's|^width=([^$]*)|\1|p')
	height=$(printf '%s' "$metadata" | sed -nE 's|^height=([^$]*)|\1|p')
	duration=$(printf '%s' "$metadata" | sed -nE 's|^duration=([^$]*)|\1|p' | tr -d '.' | sed 's/...$//')
	durationMSec=$(printf '%d' "$duration")
	size=$(printf '%s' "$metadata" | sed -nE 's|^size=([^$]*)|\1|p')

	# generate unique key for message
	uuid=$(uuidgen)
	json='{
	  "msgtype": "m.video",
	  "body": "'"$filename"'",
	  "info": {
	    "size": "'"$size"'",
	    "mimetype": "video/mp4",
	    "duration": "'"$durationMSec"'",
	    "w": "'"$width"'",
	    "h": "'"$height"'"
	  },
	  "url": "'"$file_uri"'"
	}'

	# send a message with media URI
	curl -sX PUT "$MX_URL/_matrix/client/v3/rooms/${2:-$MX_ROOM}/send/m.room.message/$uuid" -H 'Content-Type: application/json' -H 'Accept: application/json' -H "Authorization: Bearer $MX_TOKEN" -d "$json"
}

#main
link="$1"
yt_dlp_logs="${TMPDIR:-/tmp}/${0##*/}-logs"
process_file="${TMPDIR:-/tmp}/processed.mp4"
target_size_mb=10

case $(uname -o) in
	*ndroid*)
		download_dir="/sdcard"
		[ -z "$link" ] && link=$(termux-clipboard-get)
		os="droid"
		;;
	*)
		download_dir="$HOME"
		[ -z "$link" ] && link=$(wl-paste)
		os="linux"
		;;
esac

printf "\033[1;34m Video link :\033[0m %s" "$link"

info "Downloading Video.."

truncate -s0 "$yt_dlp_logs" # truncate file if exists, creates if doesn't exists

yt-dlp -S "filesize:10M" -t mp4 "$link" -o "$download_dir/%(title)s.%(ext)s" | tee "$yt_dlp_logs"

filepath=$(sed -nE "s|.*($download_dir.*\.mp4).*|\1|p" "$yt_dlp_logs" | head -1)

#shellcheck disable=SC1091
. "$HOME"/.config/.env

# load matrix creds
matrix_creds

# compresses the video file under 10 MB
[ "$(du -m "$filepath" | cut -f1)" -gt "$target_size_mb" ] && compress "$filepath"

send_matrix_msg "$filepath"

# unload matrix creds
matrix_creds "unload"

notify_$os "Video Sent to Matrix"

rm -f "$filepath" "$process_file" "$yt_dlp_logs"
exit 0
