#!/bin/bash
# info: install theme from local source or GitHub.
# options: theme [MODE] [ACTIVE]

# The function for installing a custom theme or downloading one
# from the HestiaCP theme repository.

#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

# Argument definition
theme=$1
mode=$2
active=$3

# Includes
source $HESTIA/func/main.sh
source $HESTIA/conf/hestia.conf

# Define themes repository URL format
HESTIA_THEMES_REPO="$HESTIA_GIT_REPO/$RELEASE_BRANCH/install/deb/themes"

#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

# Fallback to downloading from GitHub if no mode specified
if [ -z "$mode" ]; then
    mode="git"
fi

# Initialize local directory if it does not exist
if [ ! -d "$HESTIA_THEMES_CUSTOM" ]; then
    mkdir -p $HESTIA_THEMES_CUSTOM
fi

# Abort if no theme name specified
if [ -z "$theme" ]; then
    echo "ERROR: No theme name specified."
    echo "Usage: v-add-sys-theme theme [GIT | LOCAL] [ACTIVE]"
    echo "       theme: name of the theme to install."
    echo "       active: Set downloaded theme as active (optional)"

    exit 1
fi

# Check if theme name already exists as system theme
if [ -e $HESTIA_THEMES/$theme.css ]; then
    echo "ERROR: System theme with the same name already exists: $theme."
    exit 1
fi

# Prompt to replace existing theme if detected
if [ -e $HESTIA_THEMES_CUSTOM/$theme.css ]; then
    echo "WARNING: Theme file $theme.css already exists."
    read -p "Would you like to replace it? [Y/N] " replace_theme

    if [ "$replace_theme" = "N" ] || [ "$replace_theme" = "n" ]; then
        exit 1
    fi
fi

# Install theme from GitHub repository
if [ "$mode" = "git" ]; then
    # Check if it's a valid file first
    theme_check=$(curl -s --head -w %{http_code} $HESTIA_THEMES_REPO/$theme.css -o /dev/null)
    if [ $theme_check -ne "200" ]; then
        echo "Error: invalid theme name specified."
        exit 1
    fi

    # Download the theme file from Git
    echo "Downloading and installing theme: $theme..."
    wget $HESTIA_THEMES_REPO/$theme.css -O $HESTIA_THEMES_CUSTOM/$theme.css > /dev/null 2>&1
fi

if [ "$mode" = "local" ]; then
    read -p "Please enter the full path to the CSS file to import: " theme_path
    cp -f $theme_path $HESTIA_THEMES_CUSTOM/
fi

# Set active theme
$BIN/v-change-sys-theme $theme

#----------------------------------------------------------#
#                       Hestia                             #
#----------------------------------------------------------#

exit
