#!/bin/bash

# installer for linux
# version will be replace by sed by linux_build.sh file
version='3.4.6_125'

arch_dir="x64"
arch_in_zip="amd64"
install_dir="$HOME/.opt/hoytoba"
desktop_file_path="$HOME/.local/share/applications/hoytoba.desktop"

green="\033[0;32m"
red="\033[0;31m"
reset="\033[0m"

if [ "$(uname -m)" == "aarch64" ]; then
    arch_dir="arm64"
    arch_in_zip="arm64"
fi

url="https://storage.hoytoba.com/media/apps/linux/hoytoba_${version}_${arch_in_zip}.zip"

desktop_file="[Desktop Entry]
Name=hoytoba
Exec=$HOME/.opt/hoytoba/hoytoba
Terminal=false
Type=Application
Categories=Multimedia
Icon=$HOME/.opt/hoytoba/data/flutter_assets/assets/images/logo_round.png
"

temp_zip_file=$(mktemp)

echo -e "fetching bundle from: ${green}$url${reset} to ${green}$temp_zip_file${reset}\n"

status_code=$(curl -sLI "$url" | head -n1 | cut -d' ' -f2)
if [ "$status_code" != "200" ]; then
    echo -e "\n${red}[$status_code] failed to fetch bundle from $url${reset}\n"
    exit 1
fi

# get files
curl -L "$url" -o "$temp_zip_file"
if [ $? -ne 0 ]; then
    echo -e "\n${red}failed to download bundle${reset}\n"
    exit 1
fi

# extract files
if [ -d "${install_dir}" ]; then
    echo -e "\n${red}removing old installation${reset} from ${install_dir}"
    rm -rf "$HOME/.opt/hoytoba"
fi

if [ -f "${desktop_file_path}" ]; then
    echo -e "${red}removing old desktop file${reset} from ${desktop_file_path}"
    rm "$HOME/.local/share/applications/hoytoba.desktop"
fi

echo -e "\nextracting bundle to ${green}${install_dir}${reset}\n"

mkdir -p "$install_dir"
unzip -q -o "$temp_zip_file" -d "$install_dir"
if [ $? -ne 0 ]; then
    echo -e "\n${red}failed to extract bundle${reset}\n"
    exit 1
fi

echo -e "$desktop_file" >"$desktop_file_path"

echo -e "installed to ${green}$install_dir${reset}"
echo -e "installed desktop file to ${green}${desktop_file_path}${reset}"
echo -e "\nnow open your Application Launcher and search: ${green}hoytoba${reset}"
