#!/bin/bash 
# vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
# ############################################################
# Author: Raine Curtis raine.curtis@suse.com
# Version: 0.1.15
# Description: Set system information on desktop wallpaper
# Updated: 2023-08-16
# ############################################################

ORIGWALL=$(gsettings get org.gnome.desktop.background picture-uri)
ORIGWALL=$(echo ${ORIGWALL:8} | cut -d\' -f1)
ORIGWALLFILE=$(basename $ORIGWALL)
CFGDIR=$HOME/.config/wallfo
WALLFO_FILE=${CFGDIR}/wallfo.txt
WALLFO_IMG=${CFGDIR}/wallfo-info.png
NEWWALL="wallfo.png"
SRC_ORIGINAL="${CFGDIR}/ORIGINAL.png"
# Get current res
X=$(xrandr --current | grep '*' | uniq | awk '{print $1}' | cut -d 'x' -f1)
Y=$(xrandr --current | grep '*' | uniq | awk '{print $1}' | cut -d 'x' -f2)
CUR_RES="${X}x${Y}"
WORK_RES="${CUR_RES}"
NEWWALL="${RANDOM}-wallfo.png"
TGTDIR="$HOME/Pictures"
TGTWALL="$TGTDIR/$NEWWALL"

function show_settings () {
    show_msg "####### Settings ###########################################"
    show_msg "## Wallfo configuration dir CFGDIR:           $CFGDIR"
    show_msg "## Original wallpaper path  ORIGWALL:         $ORIGWALL"
    show_msg "## Original wallpaper file  ORIGWALLFILE:     $ORIGWALLFILE"
    show_msg "## Wallfo sysinfo file      WALLFO_FILE:      $WALLFO_FILE"
    show_msg "## Wallfo image             WALLFO_IMG:       $WALLFO_IMG"
    show_msg "## New Wallfo image         NEWWALL:          $NEWWALL"
    show_msg "## New Target image         TGTWALL:          $TGTWALL"
    show_msg "## Source orginal image     SRC_ORIGINAL:     $SRC_ORIGINAL"
}

function cleanup_wallfo () {
    if [[ "$ORIGWALLFILE" == *"wallfo.png" ]]; then
        show_msg "Cleanup wallfo env"
        rm -f $ORIGWALL
    fi
}
function backup_original_wallpaper () {
    show_msg "Checking existing wallpaper"
    if [[ "$ORIGWALLFILE" == *"xml" ]]; then
        get_wallpaper_from_xml
    fi
    # Check if wallfo is in current wallpaper name
    # if not then backup image
    show_settings
    if [[ "$ORIGWALLFILE" != *"wallfo.png" ]]; then
        show_msg "Not using wallfo.png"
        # Check for wallfo config dir
        if [[ -d $CFGDIR ]]; then
            # must be first time so copy wallpaper
            show_msg "Backing up original wallpaper in existing $CFGDIR."
	    if [[ -f "$SRC_ORIGINAL" ]]; then
            	rm -f $SRC_ORIGINAL
	    fi
        else
            # Create if needed
            mkdir -p $CFGDIR
            # Copy original wallpaper there
        fi
	# Get extension
	EXT=${ORIGWALL:(-3)}
	if [[ "$EXT" != "png" ]]; then
	    show_msg "Converting to png format"
            convert $ORIGWALL -resize $CUR_RES $SRC_ORIGINAL
        else
	    show_msg "Backing up original wallpaper"
            cp -f $ORIGWALL $SRC_ORIGINAL
	fi
    else
        show_msg "Currently using wallfo.png"
        show_msg "Original wallpaper already set"
    fi
}

function get_wallpaper_from_xml () {
    show_msg "### Getting wallpaper name from xml"
    show_msg "Current resolution: $CUR_RES"
    # Get file from xml
    # Set ORIGWALL and ORIGWALLFILE vars
    show_msg "## Original:  $ORIGWALL"
    # Check to see if current resolution is in XML
    CHKRES=$(grep "$CUR_RES" $ORIGWALL )
    show_msg "CHKRES: $CHKRES"
    if [[ -z "$CHKRES" ]]; then
            show_msg "## Current resolution not found in xml"
    	    CHKRES=$(sort -r $ORIGWALL | grep size -m1  | cut -d'>' -f2 | cut -d'<' -f1 )
    	    show_msg "CHKRES: $CHKRES"
    	    if [[ -z "$CHKRES" ]]; then
            	show_msg "Could not find valid image for resolution in xml file. Try setting a different wallpaper and run again"
        	exit 1
	    else
                ORIGWALL=$CHKRES
		show_msg "ORIGWALL set from XML: $ORIGWALL"
	    fi
    fi
    ORIGWALLFILE=$(basename $ORIGWALL)
    show_msg "## From XML:   $ORIGWALL"
}

function create_wallfo_file () {
    show_msg "Creating wallfo information"
    if [[ $MODE == "neofetch" ]] && [[ -x /usr/bin/neofetch ]] ; then
        /usr/bin/neofetch  --stdout > $WALLFO_FILE
    else
        show_msg "Creating wallfo information"
        # Clear exiting file
        cat /dev/null > $WALLFO_FILE
        #SI_KEYS=( "Hostname" "OS" "Kernel"  "Num of CPUs" "CPU Model" "Memory Total/Free" "IP Address" "DNS Servers" "Gateway" "Uptime" "Last run")
        SI_KEYS=( "Hostname" "OS" "Kernel"  "Num of CPUs" "CPU Model" "Memory Total/Avail" "IP Address" "DNS Servers" "Gateway" "Last run")
        declare -a SI_VALUES 
        # Hostname
        SI_VALUES[0]=$(hostname)
        # OS
        SI_VALUES[1]=$(grep PRETTY_NAME /etc/os-release | awk -F '"' '{print $2}')
        # Kernel
        SI_VALUES[2]=$(uname -srm)
        # CPU count
        SI_VALUES[3]=$(cat /proc/cpuinfo | grep processor | wc -l)
        # CPU Model
        SI_VALUES[4]=$(cat /proc/cpuinfo | grep "model name" | awk -F":" '{print $2}' | head -1 | sed -e 's/^ *//')
        # Memory
        SI_VALUES[5]=$(free -h | grep Mem | awk '{print $2 " / "  $7}')
        #IP Address
        SI_VALUES[6]=$(hostname -I | awk '{print $1}')
        # DNS
        SI_VALUES[7]=$(grep nameserver /etc/resolv.conf | awk '{print $2}'  | tr '\n' ';\ ')
        # GW
        SI_VALUES[8]=$(ip -4 route show default  | awk '{print $5 ": " $3}' | tr '\n' ' ')
        ## Uptime
        #SI_VALUES[9]=$(uptime)
        # Date
        SI_VALUES[9]=$(date)
        ### Write wallfo sysinfo array...
        for i in ${!SI_KEYS[@]}
        do
            printf "%+20s:   %-20s\n" "${SI_KEYS[$i]}" "${SI_VALUES[$i]}" >> $WALLFO_FILE
        done
    fi
}

function create_wallfo_png () {
    show_msg "Creating wallfo image overlay"
    rm -f $WALLFO_IMG
    cat $WALLFO_FILE | \
    #convert -font Poppins-Bold -pointsize 18 \
    convert -font Courier-Bold -pointsize 24 \
        -background none \
        -fill white \
        label:@- $WALLFO_IMG
}

function create_wallfo_wallpaper () {
    show_msg "Embedding wallfo into original wallpaper"
    show_msg "TGTWALL: $TGTWALL"
    show_msg "Current resolution: $CUR_RES"
    IMG_RES=$(identify -format '%wx%h' $SRC_ORIGINAL )
    show_msg "IMG_RES: $IMG_RES"
    if [[ "$IMG_RES" != "$CUR_RES" ]]; then
        show_msg "Converting ORIGINAL wallpaper to screen resolution"
        convert $SRC_ORIGINAL -resize $CUR_RES $SRC_ORIGINAL
        IMG_RES=$(identify -format '%wx%h' $SRC_ORIGINAL )
        show_msg "New IMG_RES: $IMG_RES"
    else
        show_msg "Wallpaper image is same as screen resolution"
    fi
    show_msg "Running: composite -gravity center \n $WALLFO_IMG \n $SRC_ORIGINAL \n $TGTWALL "
    composite  -gravity center $WALLFO_IMG $SRC_ORIGINAL $TGTWALL 
}

function set_wallfo_wallpaper () {
    show_msg "Setting wallfo wallpaper"
    show_msg "# BEFORE gsettings ---------------------------------------"
    show_msg "$(gsettings get org.gnome.desktop.background picture-uri)"
    gsettings set org.gnome.desktop.background picture-uri "file://$TGTWALL"
    show_msg "# AFTER gsettings ---------------------------------------"
    show_msg "$(gsettings get org.gnome.desktop.background picture-uri)"
    cleanup_wallfo
}

function show_msg () {
    msg=$1
    ### Uncomment to show verbose messages ###
    #echo -e "# $(date) -> $msg"
}

######################
##### Main start #####
######################
MODE=$1
backup_original_wallpaper
create_wallfo_file
create_wallfo_png
create_wallfo_wallpaper 
set_wallfo_wallpaper

