#!/bin/sh
# stolen from mitch weaver

: "${RECORD_FRAMERATE:=30}"
: "${RECORD_OUTPUT_DIR:=$PWD}"

mkdir -p /tmp/record
sock=/tmp/record/sock
pidfile=/tmp/record/pidfile

msg() { printf '* %s\n' "$*" ; }
die() { >&2 msg "$*" ; exit 1 ; }

usage() {
    die "Usage: ${0##*/} [-o output dir] [-r rate] [-f foreground]"
}

isrunning() { kill -0 "$(getpid)" 2>/dev/null ; return $? ; }

getpid() {
    [ -s $pidfile ] && read -r pid <$pidfile
    echo "${pid:-?}"
}

start() {
    isrunning && die "Another instance already exists: $(getpid)"

    file="$RECORD_OUTPUT_DIR/record-$(date "+%Y.%m.%d-%H:%M:%S").mp4"
    :>$sock

    if command -v xrectsel >/dev/null ; then
        xrectsel -f '%x %y %w %h'
    elif command -v slop >/dev/null ; then
        slop -f '%x %y %w %h'
    else
        die 'Needs xrectsel or slop'
    fi | {
        read -r x y w h

        <$sock ffmpeg -y -f x11grab -s "${w}x${h}" -r $RECORD_FRAMERATE \
        -i "${DISPLAY:-:0}+${x},${y}" -vcodec libx264 \
        -pix_fmt yuv420p -filter:v "crop=iw-mod(iw\\,2):ih-mod(ih\\,2)" \
        "$file" >/tmp/record/log 2>&1 &

        msg "recording on pid $!"

        if ${FOREGROUND:-false} ; then
            trap 'rm "$sock" /tmp/record/log 2>/dev/null ||: ; rmdir /tmp/record 2>/dev/null ||:' EXIT INT TERM
            wait
        else
            echo $! >$pidfile
            echo "$file" >/tmp/record/file
        fi
    }
}

end() {
    if isrunning ; then
        echo q >>$sock
        read -r name </tmp/record/file
        msg "Success! Saved as $name"
        rm /tmp/record/* 2>/dev/null ||:
        rmdir /tmp/record 2>/dev/null ||:
        exit
    else
        die 'Nothing being recorded.'
    fi
}

toggle() {
    if isrunning ; then
        end
    else
        start
    fi
}

while [ "$1" ] ; do
    case $1 in
        -f)
            FOREGROUND=true
            ;;
        -r)
            RECORD_FRAMERATE=$1
            ;;
        -o)
            [ -d "$2" ] || usage
            RECORD_OUTPUT_DIR=$2
            shift
            ;;
         *) usage
    esac
    shift
done

toggle