#!/bin/bash

## this app is based on one by tenner that can be downloaded at http://tenr.de/snippets/scripts/shot.sh
## it has been modified and expanded for use with MX-Fluxbox
## released under GPLv3

# mxfb-quickshot version
VERSION="2504-02"

## the following parameters are set in ${HOME}/.config/MX-Linux/mxfb-quickshot.conf
#OPTION="-s -q 100"
#DESTDIR="$(xdg-user-dir PICTURES)"
#NAME="$(date +'%y%m%d_%H%M%S')"
#SUF="png"
#PRE="quickshot_"

# check yad version and set buttons
yad_version_check=$(yad --version 2>/dev/null |  sed "s/[^0-9].*//")

if [[ $yad_version_check -gt 0 ]]; then
    yad_btn_ok='yad-ok'
    yad_btn_cancel='yad-cancel'
else
    yad_btn_ok='gtk-ok'
    yad_btn_cancel='gtk-cancel'
fi


BASE_NAME=$(basename "$0")

DATE=$(date '+%Y%m%d')
CONFIG_DIR="$HOME/.config/MX-Linux"
BACKUP_DIR="$HOME/.restore/MX-Linux"

CONFIG_NAME="mxfb-quickshot.conf"
BACKUP_NAME="${CONFIG_NAME}_${VERSION}_${DATE}"
FLUXBOXKEYS="$HOME/.fluxbox/keys"
USER_CONFIG="${CONFIG_DIR}/${CONFIG_NAME}"
DISMISS_CHK="${CONFIG_DIR}/mxfb-quickshot-dismiss.chk"

BACKUP_CONF="${BACKUP_DIR}/${BACKUP_NAME}"
SYSTEM_CONF="/usr/share/mxfb-quickshot/$CONFIG_NAME"

ICONPATH="/usr/share/icons/Papirus/24x24/devices/camera.svg"
# take icon from theme if needed
[ -e "$ICONPATH" ] || ICONPATH=camera-photo
WM_CLASS=mxfb-quickshot


# messages shown

USAGE="Usage: $BASE_NAME [-r|r|-u|u] [-png|png|-jpg|jpg]"

#set up translation

export TEXTDOMAIN=mxfb-accessories
export TEXTDOMAINDIR=/usr/share/locale
source gettext.sh

#Note: Comment lines above gettext lines are visible to translators.

# The capture of a screenshot was aborted.
NONE_SELECTED=$(gettext 'exiting, no image selected')
# The capture of a screenshot was cancelled.
CANCELLED=$(gettext 'Cancelled!')
# The capture of a screenshot was successful.
SUCCESS=$(gettext 'Success!')
# Do you want to allow a new config file to be installed?
OK_TO_PROCEED=$(gettext 'OK to proceed?')
# Do you want to display the Help message again?
DISMISS=$(gettext 'Dismiss')
DISMISS_HELP=$(gettext "Don't display the Help message again!")

# A new config file will be installed.
UPGRADE_MESSAGE=$(gettext 'This will install a new config file')

# The existing config file will be copied into a backup directory.
BACKUP_MESSAGE=$(gettext 'The existing file will be backed up in:')
MESSAGE="$UPGRADE_MESSAGE\n\n$BACKUP_MESSAGE\n\n<b>$BACKUP_DIR/</b>"

HELP_TITLE=$(gettext 'HELP: how to take a screenshot')
# How to take a screenshot...
HELP0=$(gettext 'Press "Print" (or "PrtSc") and use the mouse:')
# Press the Print-Screen-key to capture a window.
# WINDOW: press Print, then click anywhere inside
HELP1=$(gettext 'WINDOW: click anywhere inside')
# Press the Print-Screen-key to capture a wallpaper.
# DESKTOP: press Print, then click the background
HELP2=$(gettext 'DESKTOP: click the background')
# Press the Print-Screen-key to capture a screen selection.
# SELECTION: press Print, then draw a rectangle
HELP3=$(gettext 'SELECTION: draw a rectangle')

HELP_MESSAGE="

$HELP0

    --$HELP1

    --$HELP2

    --$HELP3

    "

# Hints for creating a screenshot
# The help message will not be displayed again, if user clicks on "Dismiss" button.
# The capture of a screenshot will start after closing this window.
HELP_HINTS=$(eval_gettext '
Hints

    --Click "Dismiss" to hide Help in the future!

    --Capture Help by clicking it after agreeing to proceed

    --More: search "Quickshot" in the MX Wiki')


display_help() {
    printf "%s\n" "$USAGE"
}

if [ ! -f "$DISMISS_CHK" ]; then

    HELP=(
        /usr/bin/notify-send 
        -i "$ICONPATH" 
        -t 30000 
        "$HELP_TITLE" 
        "$HELP_MESSAGE"
        )
    "${HELP[@]}"
    sleep 3

    YAD=(yad
        --title="Quickshot"
        --class="$WM_CLASS"
        --window-icon="$ICONPATH"
        --borders=20
        --center
        --fixed
        --height=300
        --width=300
        --text-align=left
        --text="\n\n<b>$HELP_HINTS</b>\n\n"
        --button="$DISMISS"'!!'"$DISMISS_HELP":3
        --button="$yad_btn_ok"
        )

    "${YAD[@]}"
    if [ $? = 3 ]; then
       [ -d "$CONFIG_DIR" ] || mkdir -p "$CONFIG_DIR"
       echo "VERSION=$VERSION" > "$DISMISS_CHK"
    fi
fi

if [ -r "$SYSTEM_CONF" ] && [ ! -r "$USER_CONFIG" ]; then
   [ -d "$CONFIG_DIR" ] || mkdir -p "$CONFIG_DIR"
   cp "$SYSTEM_CONF" "$USER_CONFIG"
   [ -d "$BACKUP_DIR" ] || mkdir -p "$BACKUP_DIR"
   cp "$USER_CONFIG" "$BACKUP_CONF"
fi

if ! ls "${BACKUP_DIR}/${CONFIG_NAME}_${VERSION}"* >/dev/null 2>&1 &&
   [ -r "$USER_CONFIG" ] && [ -r "$SYSTEM_CONF" ] &&
   ! cmp -s "$SYSTEM_CONF" "$USER_CONFIG"  ; then

    YAD=(yad
        --title="Quickshot"
        --class="$WM_CLASS"
        --window-icon="$ICONPATH"
        --width=350
        --height=200
        --borders=20
        --center
        --text-align=center
        --text="\n\n$MESSAGE\n\n"
        --button="$yad_btn_cancel":7
        --button="$OK_TO_PROCEED":6
        )

   "${YAD[@]}"
   [ $? = 6 ] || exit 0

   [ -d "$BACKUP_DIR" ] || mkdir -p "$BACKUP_DIR"
   cp "$USER_CONFIG" "$BACKUP_CONF"
   cp "$SYSTEM_CONF" "$USER_CONFIG"

fi

# using "safe-source" instead of source "$USER_CONFIG"
# safe-source - will read only allowed config parameter lines from user config
# as defined in system config. Other paramter and lines are ignored.
#
ALLOWED_CONF_PARAMETER=( $(sed -r '/^\s*[a-zA-Z_]+=/!d; s/=.*//' $SYSTEM_CONF 2>/dev/null) )
if [ ${#ALLOWED_CONF_PARAMETER[@]} != 0 ]; then
    CONF_PARAMETER_PATTERN="${ALLOWED_CONF_PARAMETER[*]}"
    CONF_PARAMETER_PATTERN="${CONF_PARAMETER_PATTERN// /|}"
    USER_CONF_PARAMETER=$(sed -r "/^\s*(${CONF_PARAMETER_PATTERN})=/!d" "$USER_CONFIG" 2>/dev/null )
    eval "$USER_CONF_PARAMETER"
fi

# user config sanity check
# set to reasonable vaules with := assignment only if not set already
: ${OPTION:="-s -q 100"}
: ${DESTDIR:=$(xdg-user-dir PICTURES)}
: ${NAME:=$(date +%y%m%d_%H%M%S)}
: ${PRE:=quickshot_}
: ${SUF:=png}
: ${TIMEOUT:=5}
: ${ICONPATH:=/usr/share/icons/Papirus/24x24/devices/camera.svg}
# take icon from theme if needed - in case user change in conf was allowed
[ -e "$ICONPATH" ] || ICONPATH=camera-photo

# use home directory if destdir is not defined
: ${DESTDIR:=$HOME}

take_shot() {
    local ret
    local filename="${PRE}${NAME}.${SUF}"
    local exec_option='mv $f '"$DESTDIR"
    [ -w "$PWD" ] || cd "$HOME"  # to make shure current directory is writable
    if [ "$(readlink -e "$DESTDIR")" = "$(readlink -e "$PWD")" ]; then
       scrot ${OPTION} "${PRE}${NAME}.${SUF}"
       ret=$?
    else
       scrot ${OPTION} "${PRE}${NAME}.${SUF}" -e "$exec_option"
       ret=$?
    fi

    if [ $ret = 1 ]; then
       /usr/bin/notify-send -i "$ICONPATH" -t 3000 "$CANCELLED"
       exit 0
    fi

    if [ $ret = 2 ] ; then
       echo "$NONE_SELECTED"
       exit 1
    fi
    return $ret
}

if [ $# -eq 0 ]; then
   take_shot &&  /usr/bin/notify-send -i "$ICONPATH" -t 3000 "    $SUCCESS"
   exit 0
fi

if [ $# -gt 2 ]; then
   display_help
   exit 1
fi

ARG1=${1#-}          # remove '-' from start of arg
case "${ARG1,,}" in  # lower case
    r|root)
        OPTION=""
        ;;
    u|focused)
        OPTION="-u"
        ;;
    *)
        display_help
        exit 1
        ;;
esac

ARG2=${2#-}          # remove '-' from start of arg
case "${ARG2,,}" in  # lower case
    jpg)
        SUF="jpg"
        ;;
    png)
        SUF="png"
        ;;
    *)
        display_help
        exit 1
        ;;
esac

take_shot
exit $?
