##  LOCAL CONFIG    ##
IP_LOCAL=change_to_client_ip
IFACE_LOCAL=change_to_client_net_iface
MODE_LOCAL=""

##  REMOTE CONFIG   ##
IP_REMOTE=change_to_server_ip
USR_REMOTE=change_to_your_username
OUTPUT_REMOTE=""
MODE_REMOTE=""

######################

# bring up local iface, comment out if not neccesary
su -c "ifconfig $IFACE_LOCAL $IP_LOCAL netmask 255.255.255.0 up"

# get local resolution
MODE_LOCAL=$(xrandr | grep \*| awk '{print $1}')

# connect to remote box with ssh
ssh $USR_REMOTE@$IP_REMOTE <<-ENDOFSCRIPT

    #set DISPLAY env var
    export DISPLAY=:0.0
    
    # get remote output name
    OUTPUT_REMOTE="\$(xrandr | grep " connected" | awk '{print \$1}')"
    
    #get all available resolution for remote box
    modes=\$( xrandr | sed -e "1,/\$OUTPUT_REMOTE/ d" \
        -e "/connected/,$ d" \
        -e "s/\([^[:space:]]\)[[:space:]].*/\1/" )
    
    #check if the desired (local) resolution is available
    if [[ \$modes == *"$MODE_LOCAL"* ]]
    then
        echo "Current resolution available";
        
        #check if desired resolution is currently used
        if [[ \$(xrandr | grep \* | awk '{print $1}') == *"$MODE_LOCAL"* ]]
        then
            echo "Desired resolution available and already in use"
        else
            echo "Desired resolution available, changing to desired"
            for m in \$modes
            do
                    if [[ \$m == *"$MODE_LOCAL"* ]]
                    then
                        xrandr --output "\$OUTPUT_REMOTE" --mode "\$m";
                    fi
            done
        fi
    else
        echo "Desired resolution not available, adding new mode and changing
        resolution";

        #calculate CVT mode
        MODE_NAME=$(cvt "$(echo $MODE_LOCAL|cut -dx -f1)" "$(echo $MODE_LOCAL|cut -dx \
            -f2)"| tail -n 1| cut -d\" -f2)
        MODE_PARAM="$(cvt "$(echo $MODE_LOCAL|cut -dx -f1)" "$(echo $MODE_LOCAL|cut -dx \
            -f2)"| tail -n 1| cut -d\" -f3)"
        
        #add new mode and change resolution
        xrandr --newmode \$MODE_NAME \$MODE_PARAM;
        xrandr --addmode "\$OUTPUT_REMOTE" "\$MODE_NAME";
        xrandr --output "\$OUTPUT_REMOTE" --mode "\$MODE_NAME";
    fi

    #start x11vnc server
    x11vnc -display :0 -usepw -listen $IP_REMOTE -bg

ENDOFSCRIPT

#start VNC viewer
xvncviewer --fullscreen "$IP_REMOTE"
