#!/bin/sh

if [[ $# -eq 0 ]] ; then
    echo "screen-connect [ -c (-N name) | -n (-N name) | -l | -h ] (-x)" >&2
    exit 1
fi

CONNECTFLAG=false
NEWFLAG=false
LISTFLAG=false
XWINFLAG=false
NAME=""

while getopts "cnlxN:h" opt
do
    case "$opt" in
        c)
            CONNECTFLAG=true
            ;;
        n)
            NEWFLAG=true
            ;;
        l)
            LISTFLAG=true
            ;;
        x)
            XWINFLAG=true
            ;;
        N)
            NAME="$OPTARG"
            ;;
        h)
            echo "screen-connect [ -c (-N name) | -n (-N name) | -l | -? ] (-x)" >&2
            exit 1
            ;;
    esac
done

if [[ $CONNECTFLAG == "true" ]] ; then
    if [[ $NAME != "" ]] ; then
        if [[ $XWINFLAG != "true" ]] ; then
            exec screen -r $NAME
        else
            exec xterm -e "screen -r $NAME"
        fi
    fi
elif [[ $NEWFLAG == "true" ]] ; then
    if [[ $NAME == "" ]] ; then
        if [[ $XWINFLAG != "true" ]] ; then
            exec screen
        else
            exec urxvto -class XTermScreen -e screen
        fi
    else
        if [[ $XWINFLAG != "true" ]] ; then
            exec screen -S $NAME
        else
            exec urxvto -class XTermScreen -e screen -S $NAME
        fi
    fi
elif [[ $LISTFLAG == "true" ]] ; then
    if [[ $XWINFLAG != "true" ]] ; then
        screen -list | sed '$ d' | sed 1d | awk '{print $1}'
    else
        if [[ -e `which rofi` ]] ; then
            NAME=`screen -list | sed '$ d' | sed 1d | awk '{print $1}' | rofi -dmenu -p "screen session"`
        else
            NAME=`screen -list | sed '$ d' | sed 1d | awk '{print $1}' | dmenu -p "screen session:"`
        fi
        [[ $NAME != "" ]] && exec urxvto -class XTermScreen -e screen -r $NAME
    fi
fi
