#!/bin/bash

name=intellij-idea-community
ver=2023.1.2
arch=amd64,arm64

Reset='\033[0m'
Bold="\e[1m"
Green='\033[0;32m'

if (( $(id -u) != 0 )); then
    echo "This package script can only be run with root (permisson denied)"
    exit
fi

extract() {
    cd /tmp || exit
    mv idea*.tar.gz /tmp/target.tar.gz
    mkdir /tmp/target
    tar xf /tmp/target.tar.gz --directory /tmp/target/
    cd /tmp/target/ || exit
}

inst() {
    echo -e "${Green}>>>${Reset}${Bold} Extracting sources ... "
    extract

    echo -e "${Green}>>>${Reset}${Bold} Installing intellij-idea-community ... "
    cp -r /tmp/target/idea* /opt/
    bash /opt/idea*/bin/idea.sh
}

upgrade() {
    echo -e "${Green}>>>${Reset}${Bold} Extracting sources ... "
    extract

    echo -e "${Green}>>>${Reset}${Bold} Removing old versions of intellij-idea-community ... "
    rm -r /opt/idea*

    echo -e "${Green}>>>${Reset}${Bold} Installing intellij-idea-community ... "
    cp -r /tmp/target/idea* /opt/
    bash /opt/idea*/bin/idea.sh
}

remove() {
    echo -e "${Green}>>>${Reset}${Bold} Removing intellij-idea-community ... "
    rm -r /opt/idea*
}

clean_tmp() {
    echo -e "${Green}>>>${Reset}${Bold} Cleaning temporary files ... "
    rm -rf /tmp/target*
    rm -f /tmp/PKGBUILD
}

if [ "$1" = "--install" ]; then
    inst
    clean_tmp

elif [ "$1" = "--upgrade" ]; then
    upgrade
    clean_tmp

elif [ "$1" = "--remove" ]; then
    remove
    clean_tmp
fi