#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
REPORTS="1"
#el_make_environment
. gettext.sh
TEXTDOMAIN="elive-tools"
export TEXTDOMAIN

# Lock system (good one) {{{
lockfile="/tmp/.$(basename $0)-${USER}.lock"

exit_ok(){
    rm -f "$lockfile"
}
exit_error(){
    rm -f "$lockfile"
}

if [[ -r "$lockfile" ]] ; then
    PROCCESS="$(cat $lockfile)"
else
    PROCCESS=" "
fi
if (ps up $PROCCESS) 1>/dev/null 2>&1 ; then
    echo -e "E: $(basename "$0" ) already running"
    exit
else
    echo $$ > "$lockfile"
fi

# traps needs to be after the lock verification, in order to not remove it when we are already running
trap "exit_ok" EXIT
trap "exit_error" 1 3 5 6 14 15 ERR TERM

# SET the lock file
echo "$$" > "$lockfile"


# end lock system }}}

ERM(){
    if [[ -n "$E_START" ]] ; then
        el_debug "disabled eremote for fonts configurations in the new versions: $@"
        #enlightenment_remote "$@"
        true
        return "$?"
    fi
    if [[ -n "$EROOT" ]] ; then
        # ignore ERM, not needed (eesh)
        true
        return "$?"
    fi
}

# INFO:
# Default sizes for the differents dpi's:
# - 96x96:  8
font_size_change(){
    # using scaling feature is good to keep the font at 8, but we can still need to configure it lower in order to optimize special_screens
    local size is_xsettingsd_running
    size="$1"

    if pidof xsettingsd 1>/dev/null 2>&1 ; then
        is_xsettingsd_running=1
        killall xsettingsd
    fi

    el_debug "setting font sizes to ${size} for GTK apps"

    # xsettingsd confs:
    sed -i -e "/FontName /s|Sans.*$|Sans $size\"|g" "$HOME/.xsettingsd"
    # gtk-3
    sed -i -e "/^gtk-font-name=/s|Sans.*$|Sans $size|g" "$HOME/.config/gtk-3.0/settings.ini"
    # gtk-2
    sed -i -e "/^gtk-font-name=/s|Sans.*$|Sans $size\"|g" "$HOME/.gtkrc-2.0"

    # urxvt size:
    # should be statically set to 10 ?? i think it doesn't change
    #sed -i -e "s|pixelsize=.*$|pixelsize=$(( $size + 2 ))|g" "$HOME/.Xdefaults"

    # conky font size change?
    #sed -i -e 's|:size=8|:size=7|g' "$HOME/.conkyrc"

    # always restart conky, it needs to refresh the font sizes
    #is_restart_needed_conky=1


    # load settings
    #xrdb -merge "$HOME/.Xdefaults"

    if ((is_xsettingsd_running)) ; then
        ( xsettingsd 1>/dev/null 2>&1 & )
    fi
}

special_screens(){
    # defaults
    resolution="$( el_resolution_get )"
    resolution_h="${resolution%%x*}"
    resolution_v="${resolution##*x}"
    font="DejaVu Sans"

    # e17
    if [[ -n "$E_START" ]] && [[ "$E_HOME_DIR" = "$HOME/.e/e17" ]] ; then
        # check
        if [[ "$( enlightenment_remote -ping )" != *pong ]] ; then
            el_error "Unable to connect to DBUS enlightenment_remote"
            exit 1
        fi

        # get the optimal font name
        if enlightenment_remote -font-list | grep -Fqs "DejaVu Sans:" ; then
            font="DejaVu Sans"
        else
            font="Sans"
        fi

        # automatically set the Font for applications in an optimal size based in the DPI:
        enlightenment_remote -font-set-auto "application" "$font"

        el_debug "set font for E17+ as: $font"

        #resolution="$( enlightenment_remote -resolution-get )"
        #read -r resolution <<< "$resolution"
        #resolution_h="${resolution%%x*}"
        #resolution_v="${resolution##*x}"
    fi


    # this should be the default for all dpi's with the new scaling system:
    #font_size_change "8"
    # el_dpi_get in mode lowered en 157
    #font_size_change "9"
    # el_dpi_get in mode lowered en 96
    font_size_change "8"

    # set more specific font sizes for extreme cases
    if [[ "$resolution_h" -le 1024 ]] ; then
        # disable google chrome bookmarks due to size limitations (only in live due to sudo)
        for i in "$HOME/.config/google-chrome/Default/Preferences" "$HOME/.config/chromium/Default/Preferences" "/etc/chromium/master_preferences" "/etc/google-chrome/master_preferences" "/etc/skel/.config/google-chrome/Default/Preferences" "/etc/skel/.config/chromium/Default/Preferences"
        do
            el_debug "setting 'show_on_all_tabs' to 'false' for: '$i'"
            if grep -Fqs "boot=live" /proc/cmdline ; then
                sudo -H sed -i -e "s|^.*\"show_on_all_tabs\":.*$|\"show_on_all_tabs\":false|g" "$i" 2>/dev/null
                sudo -H sed -i -e "s|^.*\"show_on_all_tabs\" :.*$|\"show_on_all_tabs\" : false|g" "$i" 2>/dev/null
            else
                sed -i -e "s|^.*\"show_on_all_tabs\":.*$|\"show_on_all_tabs\":false|g" "$i" 2>/dev/null || true
                sed -i -e "s|^.*\"show_on_all_tabs\" :.*$|\"show_on_all_tabs\" : false|g" "$i" 2>/dev/null || true
            fi
        done

        # update hexchat fonts
        sed -i -e 's|^text_font = .*|text_font = Monospace 8|g' "$HOME/.config/hexchat/hexchat.conf"
        is_restart_needed_hexchat=1
    fi

    #if [[ "$resolution_h" -ge 800 ]] ; then
        ## resolutions between 800x* & 1024x*
        #ERM -font-set "application" "$font" 8
        #font_size_change "8"
    #fi
    if [[ "$resolution_h" -le 800 ]] ; then
        # very extreme cases (very small screens)
        ERM -font-set "application" "$font" 7
        font_size_change "7"
        # conky small screens configurations:
        sed -i -e 's|:size=8|:size=7|g' "$HOME/.conkyrc"
        sed -i -e '/^$/d' "$HOME/.conkyrc"
        is_restart_needed_conky=1
        el_debug "setting conky to use a small font size (8 -> 7)"

        # update hexchat fonts
        sed -i -e 's|^text_font = .*|text_font = Monospace 7|g' "$HOME/.config/hexchat/hexchat.conf"
        is_restart_needed_hexchat=1
    fi

    # load settings
    #xrdb -merge "$HOME/.Xdefaults"
}

update_scaling(){
    # if was not configured yet
    #if ! grep -qs "^Xft.dpi: [[:digit:]]" "$HOME/.Xdefaults" ; then
        # Set scaling factor into Xdefaults
        sed -i -e '/Xft.dpi:/d' "$HOME/.Xdefaults"
        echo "Xft.dpi: ${dpi%x*}" >> "$HOME/.Xdefaults"
        is_restart_needed_e16=1
        el_debug "seting dpi '${dpi%x*}' on ~/.Xdefaults"
    #fi

    # cursor size, should be not needed because is already dynamic by dpi
    #sed -i -e '/Xcursor.size:/d' "$HOME/.Xdefaults"
    #echo "Xcursor.size: 48" >> "$HOME/.Xdefaults"

    # DEFAULT cursor theme forced:
    if ! grep -qs "^Xcursor.theme: [[:alnum:]]" "$HOME/.Xdefaults" ; then
        if [[ -d "/usr/share/icons/Breeze_Snow/cursors" ]] ; then
            sed -i -e '/Xcursor.theme:/d' "$HOME/.Xdefaults"
            echo "Xcursor.theme: Breeze_Snow" >> "$HOME/.Xdefaults"
            is_restart_needed_e16=1
            el_debug "setting cursor theme to Breeze_Snow"
        else
            if [[ -d "/usr/share/icons/whiteglass/cursors" ]] ; then
                sed -i -e '/Xcursor.theme:/d' "$HOME/.Xdefaults"
                echo "Xcursor.theme: whiteglass" >> "$HOME/.Xdefaults"
                is_restart_needed_e16=1
                el_debug "setting cursor theme to whiteglass"
            fi
        fi
    fi

    # set default scale factor value for specific apps and confs
    scale_factor="$( echo "scale=4 ; ${dpi%x*} / 96" | LC_ALL=C bc -l )"

    if echo "$scale_factor" | grep -qs "[[:digit:]]" ; then
        # set gsettings (saved in ~/.config/dconf/user )
        # INFO: https://wiki.archlinux.org/title/HiDPI
        #gsettings set org.gnome.desktop.interface text-scaling-factor "${scale_factor}"

        # set elementary and all E to use the same scaling:
        elementary_config -q -s "${scale_factor}"
        is_reload_elementary_needed=1
        el_debug "setting ELM to the scale factor '${scale_factor}'"

        # set urxvt to a specific size
        # FIXME: this is overwritten after aparently
        rxvt_font_size="$( echo "9 * ${scale_factor}" | LC_ALL=C bc -l | sed -e 's|\..*$||g' )"
        sed -i -e "s|pixelsize=.*$|pixelsize=${rxvt_font_size}|g" "$HOME/.Xdefaults"
        el_debug "setting URXVT font size to '${rxvt_font_size}'"

        # cairo-dock size, 34 value is the default size we used to have
        cairo_dock_icon_size="$( echo "34 * ${scale_factor}" | LC_ALL=C bc -l | sed -e 's|\..*$||g' )"
        sed -i -e "s|^launcher size=.*$|launcher size=${cairo_dock_icon_size};${cairo_dock_icon_size};|g" "$HOME/.config/cairo-dock/current_theme/cairo-dock.conf"
        cairo_dock_zoom_space="$( echo "175 * ${scale_factor}" | LC_ALL=C bc -l | sed -e 's|\..*$||g' )"
        sed -i -e "s|^sinusoid width=.*$|sinusoid width=${cairo_dock_zoom_space}|g" "$HOME/.config/cairo-dock/current_theme/cairo-dock.conf"
        is_restart_needed_cairodock=1
        el_debug "setting Cairo-Dock to: icon size '${cairo_dock_icon_size}', zoom space '${cairo_dock_zoom_space}'"

        # thunar sizes:
        thunar_separator_position="$( echo "180 * ${scale_factor}" | LC_ALL=C bc -l | sed -e 's|\..*$||g' )"
        thunar_window_width="$( echo "640 * ${scale_factor}" | LC_ALL=C bc -l | sed -e 's|\..*$||g' )"
        thunar_window_height="$( echo "490 * ${scale_factor}" | LC_ALL=C bc -l | sed -e 's|\..*$||g' )"
        sed -i -e "/last-separator-position/s/value=\".*\"/value=\"${thunar_separator_position}\"/g" "$HOME/.config/xfce4/xfconf/xfce-perchannel-xml/thunar.xml"
        sed -i -e "/last-window-width/s/value=\".*\"/value=\"${thunar_window_width}\"/g" "$HOME/.config/xfce4/xfconf/xfce-perchannel-xml/thunar.xml"
        sed -i -e "/last-window-height/s/value=\".*\"/value=\"${thunar_window_height}\"/g" "$HOME/.config/xfce4/xfconf/xfce-perchannel-xml/thunar.xml"
        el_debug "setting Thunar to: separator position '${thunar_separator_position}', window width '${thunar_window_width}', window height '${thunar_window_height}'"

        # chromium / chrome zooms are very big by default, improve them:
        if ! ((is_no_chrome)) ; then
            # reconfigure chrome / chromium zoom values: {{{

            # default values to resize the conf
            # 150 % = 2.223901085741545
            # 125 % = 1.2239010857415449
            # 110 % = 0.5227586988632231
            # 100 % = 0.0
            # 90 % = -0.5778829311823857
            # 80 % = -1.2239010857415447
            # 75 % = -1.5778829311823859
            # 67 % = -2.2239010857415455
            # 50 % = -3.8017840169239308
            # 33 % = -6.025685102665476
            # 25 % = -7.6035680338478615

            scale_percent="$( echo "$scale_factor * 100" | LC_ALL=C bc -l | sed -e 's|\..*$||g' )"
            chrome_zoom_percent="$( echo "scale=4 ; 100 / ( ${dpi%x*} / 96 )" | LC_ALL=C bc -l | sed -e 's|\..*$||g' )"

            if [[ -n "$chrome_zoom_percent" ]] ; then
                if [[ "${chrome_zoom_percent}" -le "25" ]] ; then
                    chrome_zoom_value="-7.6035680338478615"
                elif [[ "${chrome_zoom_percent}" -le "33" ]] ; then
                    chrome_zoom_value="-6.025685102665476"
                elif [[ "${chrome_zoom_percent}" -le "50" ]] ; then
                    chrome_zoom_value="-3.8017840169239308"
                elif [[ "${chrome_zoom_percent}" -le "67" ]] ; then
                    chrome_zoom_value="-2.2239010857415455"
                elif [[ "${chrome_zoom_percent}" -le "75" ]] ; then
                    chrome_zoom_value="-1.5778829311823859"
                elif [[ "${chrome_zoom_percent}" -le "80" ]] ; then
                    chrome_zoom_value="-1.2239010857415447"
                elif [[ "${chrome_zoom_percent}" -le "90" ]] ; then
                    chrome_zoom_value="-0.5778829311823857"
                elif [[ "${chrome_zoom_percent}" -le "100" ]] ; then
                    chrome_zoom_value="0.0"
                elif [[ "${chrome_zoom_percent}" -le "110" ]] ; then
                    chrome_zoom_value="0.5227586988632231"
                elif [[ "${chrome_zoom_percent}" -le "125" ]] ; then
                    chrome_zoom_value="1.2239010857415449"
                elif [[ "${chrome_zoom_percent}" -le "150" ]] ; then
                    chrome_zoom_value="2.223901085741545"
                fi
            fi

            # }}}
            if pidof chromium 1>/dev/null 2>&1 ; then
                killall -9 chromium
                sync ; sleep 2
            fi
            if pidof chrome 1>/dev/null 2>&1 ; then
                killall -9 chrome
                sync ; sleep 2
            fi
            # update confs
            perl -p -i -e "s|{\"default_zoom_level\":\{\"x\":(-?)([[:digit:]].*?},)|{\"default_zoom_level\":{\"x\":${chrome_zoom_value}},|" "$HOME/.config/google-chrome/Default/Preferences" 1>/dev/null 2>&1 || true
            perl -p -i -e "s|{\"default_zoom_level\":\{\"x\":(-?)([[:digit:]].*?},)|{\"default_zoom_level\":{\"x\":${chrome_zoom_value}},|" "$HOME/.config/chromium/Default/Preferences" 1>/dev/null 2>&1 || true

            el_debug "setting Chromium / Chrome Zoom value to ${chrome_zoom_percent} % to avoid websites to look huge and cramped"
        fi
    fi

}

main(){
    # args {{{

    #defaults
    is_reload_wanted=1


    if [[ -n "$1" ]] ; then
        for arg in "$@"
        do
            case "$arg" in
                -a|--auto)
                    is_auto=1
                    shift
                    ;;
                -q|--quiet)
                    is_guide_mode=0
                    shift
                    ;;
                --no-reload)
                    unset is_reload_wanted
                    shift
                    ;;
                --no-chromium|--no-chrome)
                    unset is_no_chrome=1
                    shift
                    ;;
            esac
        done
    fi

    # }}}

    if ((is_auto)) ; then
        # fetch machine dpi
        dpi="$( el_dpi_get "lowered" )"
        el_debug "detected DPI (suggested) ${dpi}"
        # premature exit
        if [[ "${dpi}" != *"x"* ]] ; then
            el_error "unable to get machine DPI: $( el_dpi_get 'lowered' 2>&1)"
            return 0
        fi
    else
        dpi_lowered="$( el_dpi_get "lowered" )"
        # max_value="$( echo "${dpi_lowered%x*} * 1.8" | LC_ALL=C bc -l )"
        max_value="$( echo "${dpi_lowered%x*} * 2.4" | LC_ALL=C bc -l )"
        max_value="${max_value%.*}"
        el_debug "detected DPI (suggested) ${dpi_lowered}, max DPI suggested for your screen: ${max_value}"
        # get confs
        el_config_get
        # defaults
        if [[ -z "$conf_selected_dpi" ]] ; then
            conf_selected_dpi="${dpi_lowered%x*}"
        fi

        local message_select
        message_select="$( printf "$( eval_gettext "Select the DPI of your screen. This value will resize the elements on your desktop according to its percentage." )" "" )"
        #local message_select_extra
        #message_select_extra="$( printf "$( eval_gettext "Point 'A' is the default value of most common screens, select it to optimize your pixels and dimension. Point 'B' is the suggested value for your screen. Point 'C' is the real DPI value of your screen, we suggest a lower value than this one to be able to visualize more elements in your desktop." )" "" )"
        local message_default
        message_default="$( printf "$( eval_gettext "Traditional" )" "" ) 96"
        local message_suggested
        message_suggested="$( printf "$( eval_gettext "Recommended" )" "" ) ${dpi_lowered%x*}"
        local message_yourscreen
        message_yourscreen="$( printf "$( eval_gettext "Your Screen" )" "" ) $( el_dpi_get | sed -e 's|x.*$||g' )"


        if [[ "${dpi_lowered%x*}" -gt 90 ]] && [[ "${dpi_lowered%x*}" -lt 110 ]] ; then
            result="$(
            yad --width=600 --height=200 --center --on-top \
                --image-on-top --image=preferences-desktop-display \
                --title="$( eval_gettext "Desktop Size" )" \
                --text="$( eval_gettext "${message_select}" )" \
                --scale --value="$conf_selected_dpi" --min-value=60 --max-value=${max_value} --step=1 --inc-buttons --mark="${message_default}:96" \
                $NULL || echo cancel )"
        else
            result="$(
            yad --width=260 --height=480 --center --on-top \
                --image-on-top --image=preferences-desktop-display \
                --title="$( eval_gettext "Desktop Size" )" \
                --text="$( eval_gettext "${message_select}\n\n${message_select_extra}" )" \
                --scale --value="$conf_selected_dpi" --min-value=60 --max-value=${max_value} --step=1 --inc-buttons --vertical --mark="${message_default}:96" --mark="${message_suggested}:${dpi_lowered%x*}" \
                $NULL || echo cancel )"
        fi

        #--scale --value="$conf_selected_dpi" --min-value=60 --max-value=${max_value} --step=1 --inc-buttons --mark="A:96" --mark="C:$( el_dpi_get | sed -e 's|x.*$||g' )"  --mark="B:${dpi_lowered%x*}" \
        #--scale --value="$conf_selected_dpi" --min-value=60 --max-value=${max_value} --step=1 --inc-buttons --vertical --mark="${message_default}:96" --mark="${message_yourscreen}:$( el_dpi_get | sed -e 's|x.*$||g' )"  --mark="${message_suggested}:${dpi_lowered%x*}" \

        if [[ -n "$result" ]] && [[ "$result" != "cancel" ]] ; then
            #dpi="$( echo "${result}" | awk -v FS="|" '{print $1}' )"
            dpi="${result}x${result}"

            # save confs
            conf_selected_dpi="$result"
            el_config_save "conf_selected_dpi"
        fi
    fi

    # update sizes
    if [[ "${dpi}" != *"x"* ]] ; then
        zenity --error --text="Wrong value inserted"
        exit 1
    fi

    update_scaling
    special_screens

    # load new settings
    xrdb -merge "$HOME/.Xdefaults"

    if ((is_reload_wanted)) ; then
        # ignore reloading e16 if nothing changed
        if [[ "$scale_factor" = "1.00"* ]] && [[ "$dpi" = "96x96" ]] ; then
          unset is_restart_needed_e16
        fi

        # reload desktop
        if ((is_restart_needed_e16)) ; then
            if [[ -n "$EROOT" ]] ; then
                eesh save_config
                el_debug "restarting E16"
                eesh restart
            fi
        fi

        if ((is_restart_needed_hexchat)) ; then
            if pidof hexchat 1>/dev/null ; then
                killall hexchat
                el_debug "restarting hexchat"
                ( hexchat 1>/dev/null 2>&1 & disown )
            fi
        fi


        if ((is_restart_needed_conky)) ; then
            if pidof conky 1>/dev/null ; then
                killall conky
                el_debug "restarting conky"
                ( conky 1>/dev/null 2>&1 & disown )
            fi
        fi
        if ((is_restart_needed_cairodock)) ; then
            if pidof cairo-dock 1>/dev/null ; then
                killall cairo-dock 1>/dev/null 2>&1
                killall -9 cairo-dock 1>/dev/null 2>&1
                el_debug "restarting cairo-dock"
                ( cairo-dock 1>/dev/null 2>&1 & disown )
            fi
        fi
    fi

    # save confs
    if [[ -n "$E_START" ]] ; then
        ERM -save
    fi


    # TODO: this is an actual bug, remove later:  https://phab.enlightenment.org/T8930
    if ((is_reload_elementary_needed)) ; then
        # refresh:
        ( sync ; sleep 1 ; elementary_config -q ; ) &
    fi

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
