#!/bin/bash

function error {
  echo -e "\e[91m$1\e[39m"
  exit 1
}

cd "$HOME"

#ensure non-root
if [[ "$(id -u)" == 0 ]]; then
  error "Artian-Apps is not designed to be installed as root! Please try again as a regular user."
fi

#ensure debian
command -v apt >/dev/null || error "apt: command not found. Most likely this system is not running Debian."

#Ensure running arm processor
if uname -m | grep -qi 'x86\|i686\|i386' ;then
  error "Artian-Apps is not supported on non-ARM CPU architectures. We encourage you to use your distro's app store, like Gnome Software or Discover Software Center."
fi

sudo apt update || error "The command 'sudo apt update' failed. Before Artian-Apps will work, you must fix your apt package-management system."

#install dependencies
dependencies='yad curl wget aria2 lsb-release software-properties-common apt-utils apt-transport-https gnupg imagemagick bc librsvg2-bin locales shellcheck git wmctrl xdotool x11-utils rsync'

if ! dpkg -s $dependencies &>/dev/null ;then
  sudo apt install $dependencies -y -f --no-install-recommends
fi
echo

#remove annoying "YAD icon browser" launcher
sudo rm -f /usr/share/applications/yad-icon-browser.desktop

#download Artian-apps if folder missing
DIRECTORY="$(readlink -f "$(dirname "$0")")"
if [ -z "$DIRECTORY" ] || [ "$DIRECTORY" == "$HOME" ] || [ "$DIRECTORY" == bash ] || [ ! -f "${DIRECTORY}/api" ] || [ ! -f "${DIRECTORY}/gui" ];then
  DIRECTORY="$HOME/Artian-apps"
fi
downloaded=0 #track if Artian-apps was downloaded this time

#Re-download Artian-apps folder in all cases if Artian-apps already exists
#users expect to use the install script to "restore" a working Artian-apps install in incase their local version is somehow not working or corrupted
if [ -d "$DIRECTORY" ];then    
  rm -rf ~/Artian-apps-forced-update
  
  echo "Reinstalling Artian-Apps..."
  
#if Artian-apps folder does not exist, download it
elif [ ! -d "$DIRECTORY" ];then
  echo "Downloading Artian-Apps..."
  downloaded=1
  output="$(git clone --depth 1 https://git.fdc.abrish.ir/a.kamyar/PublicFiles/ "$DIRECTORY" 2>&1)"
  if [ $? != 0 ] || [ ! -d "$DIRECTORY" ];then
    error "Artian-Apps download failed!\ngit clone output was: $output"
  fi
  #click new installation analytics link
  curl -s -X 'GET' "https://git.fdc.abrish.ir/a.kamyar/PublicFiles/Artian-Apps/" -H 'accept: image/gif' -A "Artian-Apps  a software manager for Artian company" >/dev/null &
fi

#Past this point, DIRECTORY variable populated with valid ARtian-apps directory

#if ChromeOS, install lxterminal
if command -v garcon-terminal-handler >/dev/null ;then
  echo "In order to install apps on ChromeOS, a working terminal emulator is required.
Installing lxterminal in 10 seconds... (press Ctrl+C to cancel)"
  sleep 10
  sudo apt install -yf lxterminal || error "Failed to install lxterminal on ChromeOS!"
fi

#menu button
if [ ! -f ~/.local/share/applications/Artian-apps.desktop ];then
  echo "Creating menu button..."
fi
mkdir -p ~/.local/share/applications
if [ -f /etc/xdg/menus/lxde-pi-applications.menu ];then #If on PiOS, place launcher in Accessories as it has always been there and is more intuitive there
echo "[Desktop Entry]
Name=Artian-Apps
Comment=Artian-Apps Software manager for Artian Company
Exec=${DIRECTORY}/gui
Icon=${DIRECTORY}/icons/logo.png
Terminal=false
StartupWMClass=Artian-Apps
Type=Application
Categories=Utility
StartupNotify=true" > ~/.local/share/applications/Artian-apps.desktop
else #if not on PiOS, place launcher in Preferences to match the wider decision of putting app installers there (see PR #2388)
echo "[Desktop Entry]
Name=Artian-Apps
Comment=Artian-Apps a Software manager for Artian Company
Exec=${DIRECTORY}/gui
Icon=${DIRECTORY}/icons/logo.png
Terminal=false
StartupWMClass=Artian-Apps
Type=Application
Categories=Utility;System;PackageManager;
StartupNotify=true" > ~/.local/share/applications/Artian-apps.desktop
fi
chmod 755 ~/.local/share/applications/Artian-apps.desktop
gio set ~/.local/share/applications/Artian-apps.desktop "metadata::trusted" yes

#copy menu button to Desktop
mkdir -p ~/Desktop
cp -f ~/.local/share/applications/Artian-apps.desktop ~/Desktop/

chmod 755 ~/Desktop/Artian-apps.desktop
gio set ~/Desktop/Artian-apps.desktop "metadata::trusted" yes

#settings menu button
if [ ! -f ~/.local/share/applications/Artian-apps-settings.desktop ];then
  echo "Creating Settings menu button..."
fi
echo "[Desktop Entry]
Name=Artian-Apps Settings
Comment=Configure Artian-Apps or create an App
Exec=${DIRECTORY}/settings
Icon=${DIRECTORY}/icons/settings.png
Terminal=false
StartupWMClass=Artian-Apps-Settings
Type=Application
Categories=Settings;
StartupNotify=true" > ~/.local/share/applications/Artian-apps-settings.desktop

if [ ! -f ~/.config/autostart/Artian-apps-updater.desktop ];then
  echo "Creating autostarted updater..."
fi
mkdir -p ~/.config/autostart
echo "[Desktop Entry]
Name=Artian-Apps Updater
Exec=${DIRECTORY}/updater onboot
Icon=${DIRECTORY}/icons/logo.png
Terminal=false
StartupWMClass=Artian-Apps
Type=Application
X-GNOME-Autostart-enabled=true
Hidden=false
NoDisplay=false" > ~/.config/autostart/Artian-apps-updater.desktop

mkdir -p "${DIRECTORY}/data/status" "${DIRECTORY}/data/update-status" \
  "${DIRECTORY}/data/preload" "${DIRECTORY}/data/settings" \
  "${DIRECTORY}/data/status" "${DIRECTORY}/data/update-status" \
  "${DIRECTORY}/data/categories"

#Artian-apps terminal command
if [ ! -f /usr/local/bin/Artian-apps ] || ! cat /usr/local/bin/Artian-apps | grep -q "${DIRECTORY}/gui" ;then
  echo "#!/bin/bash
${DIRECTORY}/gui"' "$@"' | sudo tee /usr/local/bin/Artian-apps >/dev/null
  sudo chmod +x /usr/local/bin/Artian-apps
fi

#preload app list
if [ ! -f "$DIRECTORY/data/preload/LIST-" ];then
  echo "Preloading app list..."
fi
"${DIRECTORY}/preload" yad &>/dev/null

#Run runonce entries
"${DIRECTORY}/etc/runonce-entries" &>/dev/null

#Determine message of the day. If announcements file missing or over a day old, download it.
if [ ! -f "${DIRECTORY}/data/announcements" ] || [ ! -z "$(find "${DIRECTORY}/data/announcements" -mtime +1 -print)" ]; then
  wget https://git.fdc.abrish.ir/a.kamyar/PublicFiles/Artian-Apps/ -qO "${DIRECTORY}/data/announcements"
fi

if [ $downloaded == 1 ];then
  echo "Installation complete. Artian-Apps can be launched from the start menu or by running the command 'Artian-apps'."
else
  echo -e "Please note that Artian-Apps has NOT been freshly downloaded, because $DIRECTORY already exists."
fi
