#!/bin/bash

if [[ "$1" == "--help" ]] ; then
    echo "Usage: set-directory-icon <folder> <icon>"
    exit
fi

DIRECTORY="$1"
ICON="$2"

if [[ ! -d "$DIRECTORY" ]] ; then
    echo "Directory does not exist"
    exit 2
fi

if ! printf "%s" "$ICON" | grep -Pq '^[a-zA-Z0-9_-]+$' ; then
    echo "Invalid Icon name"
    exit 2
fi

if [[ ! -f "$DIRECTORY/.directory" ]] ; then
    printf "[Desktop Entry]\nIcon=%s\n" "$ICON" > "$DIRECTORY/.directory"
else
    sed 's/Icon=.*/Icon='"$ICON/" -i "$DIRECTORY/.directory"
fi

touch "$DIRECTORY"
