#!/bin/bash
#
# $LVDS_DEVICE Rotate
# Andrew Wyatt
# Tool to rotate $LVDS_DEVICE panel
#

JUPITER_PATH="/usr/lib/jupiter/scripts"
JUPITER_VAR="/var/jupiter"

if [[ "$*" =~ "silent" ]]; then
  NO_NOTIFY=1
fi

. $JUPITER_PATH/notify

NICON="/usr/share/pixmaps/jupiter/rotate.png"

if [ ! -d "$JUPITER_VAR" ]; then
  mkdir $JUPITER_VAR
fi

VDEV=$(xrandr | grep " connected [0-9]" | awk '{print $1}' | head -n 1)

LVDS_DEVICE=$(xrandr | grep " connected" | awk '{print $1}' | grep $VDEV)

function rotate_toggle {
  CURRENT=$(xrandr  | grep $LVDS_DEVICE | awk '{print $4}' | sed s#^\(##)
  if [ "$CURRENT" = "left" ]; then
    $JUPITER_PATH/resolutions default
    ROTATION="inverted"
    RTOUCHPAD=2
  elif [ "$CURRENT" = "inverted" ]; then
    $JUPITER_PATH/resolutions default
    ROTATION="right"
    RTOUCHPAD=3
  elif [ "$CURRENT" = "right" ]; then
    ROTATION="normal"
    RTOUCHPAD=0
  else
    $JUPITER_PATH/resolutions default
    ROTATION="left"
    RTOUCHPAD=1
  fi
  if [ "$ROTATION" ]; then
    echo "$ROTATION $RTOUCHPAD" > $JUPITER_VAR/rotation_saved
    rotate_lvds $ROTATION $RTOUCHPAD
  fi
}

function restore_rotation {
  if [ -e "$JUPITER_VAR/rotation_saved" ]; then
    CURRENT=$(xrandr  | grep $LVDS_DEVICE | awk '{print $4}' | sed s#^\(##)
    RMODES=$(cat $JUPITER_VAR/rotation_saved)
    ROTATION=$(echo $RMODES | awk '{print $1}')
    RTOUCHPAD=$(echo $RMODES | awk '{print $2}')
    if [ ! "$CURRENT" = "$ROTATION" ]; then
      NO_NOTIFY=1
      if [ ! "$CURRENT" = "normal" ]; then
        $JUPITER_PATH/resolutions default
      fi
      rotate_lvds $ROTATION $RTOUCHPAD
    fi
  fi
}

function rotate_lvds {
    if [ ! "$3" = "silent" ]; then
      notify $"Rotate LCD \"$1\"" $NICON
    else
      NO_NOTIFY=1
    fi
    CURRENT=$(xrandr  | grep $LVDS_DEVICE | awk '{print $4}' | sed s#^\(##)
    if [ ! "$1" = "normal" ]; then
      $JUPITER_PATH/resolutions default
    fi
    xrandr --output $LVDS_DEVICE --rotate "$1"
    synclient orientation=$2 2>/dev/null
    echo "$1 $2" > $JUPITER_VAR/rotation_saved
}

case $1 in
  inverted)
    rotate_lvds inverted 2
  ;;
  left)
    rotate_lvds left 1
  ;;
  right)
    rotate_lvds right 3
  ;;
  normal)
    rotate_lvds normal 0
  ;;
  default)
    rotate_lvds normal 0 silent
  ;;
  restore)
    restore_rotation
  ;;
  *)
    rotate_toggle
  ;;
esac
