#!/usr/bin/env bash

msg() {
    printf '>>> %s\n' "$@" >&2
}

dir=$(clipctl cache-dir)
cache_file=$dir/line_cache

log=$(mktemp)
tim=$(mktemp)
clipmenu_shim=$(mktemp)
num_files=1500

trap 'rm -f -- "$log" "$tim" "$clipmenu_shim"' EXIT

if [[ $0 == /* ]]; then
    location=${0%/*}
else
    location=$PWD/${0#./}
    location=${location%/*}
fi

msg 'Setting up edited clipmenu'

cat - "$location/../clipmenu" > /tmp/clipmenu << EOF
#!/usr/bin/env bash

exec 3>&2 2> >(tee "$log" |
                 sed -u 's/^.*$/now/' |
                 date -f - +%s.%N > "$tim")
set -x

dmenu() { :; }
xsel() { :; }

EOF

chmod a+x /tmp/clipmenu

if ! (( NO_RECREATE )); then
    rm -rf "$dir"
    mkdir -p "$dir"

    msg "Writing $num_files clipboard files"

    for (( i = 0; i <= num_files; i++ )); do
        (( i % 100 )) || printf '%s... ' "$i"

        line_len=$(( (RANDOM % 10000) + 1 ))
        num_lines=$(( (RANDOM % 10) + 1 ))
        data=$(
            tr -dc 'a-zA-Z0-9' < /dev/urandom |
                fold -w "$line_len" |
                head -"$num_lines"
        )
        read -r first_line_raw <<< "$data"
        printf -v first_line '%s (%s lines)\n' "$first_line_raw" "$num_lines"
        printf '%d %s' "$i" "$first_line" >> "$cache_file"
        fn=$dir/$(cksum <<< "$first_line")
        printf '%s' "$data" > "$fn"
    done

    printf 'done\n'
else
    msg 'Not nuking/creating new clipmenu files'
fi

msg 'Running modified clipmenu'

time /tmp/clipmenu

(( TIME_ONLY )) && exit 0

msg 'Displaying perf data'

# modified from http://stackoverflow.com/a/20855353/945780
paste <(
    while read -r tim ;do
        [ -z "$last" ] && last=${tim//.} && first=${tim//.}
        crt=000000000$((${tim//.}-10#0$last))
        ctot=000000000$((${tim//.}-10#0$first))
        printf "%12.9f %12.9f\n" ${crt:0:${#crt}-9}.${crt:${#crt}-9} \
                                 ${ctot:0:${#ctot}-9}.${ctot:${#ctot}-9}
        last=${tim//.}
      done < "$tim"
) "$log" | less
