#!/bin/fish
set parts (string split / $argv[1])
set protocol $parts[1]
set action $parts[3]
set secret $parts[4]

function die
    notify-send -u critical -t 5000 'Jellynative Error' $argv[1]
    exit 1
end

function player
    notify-send -u low -t 1000 Jellynative 'Player ist launching...'
    if not mpv --http-header-fields=(echo -s 'Cookie: session=' $argv[1]) $argv[3..] $argv[2]
        die 'Player exited with error code'
    end
end

if not test $protocol = "jellynative:"
    die "Wrong protocol"
end

set config_dir $XDG_CONFIG_HOME
if test -z $config
    set config_dir ~/.config
end
set config $config_dir/jellynative_secret
if not test -e $config
    head -c 16 /dev/urandom | xxd -p >$config
end
set secret (cat $config)

if test $action != show-secret-v1
    if test $secret != $parts[4]
        die 'Incorrect secret'
    end
end

switch $action
    case show-secret-v1
        notify-send -u low Jellynative "Secret: $secret"
    case player-v2
        player $parts[5] (string join / $parts[7..]) --seek=$parts[6]
    case player-fullscreen-v2
        player $parts[5] (string join / $parts[7..]) --fullscreen --start=$parts[6]
    case '*'
        die 'Unknown action'
end
