#!/bin/bash

name=micro
ver=git
arch=all
dep_apt="make golang unzip"
dep_apk="make go unzip"

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

if ! [ -f "/usr/bin/apt" ] && ! [ -f "/sbin/apk" ]; then
    echo "This build script cannot be executed on your system. Sorry"
    exit
fi

[[ -f "/usr/bin/apt" ]] && pkg_mgr="apt"
[[ -f "/sbin/apk" ]] && pkg_mgr="apk"

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

get_dependencies() {
    [[ "${pkg_mgr}" == "apt" ]] && cmd="apt install -y $dep_apt"
    [[ "${pkg_mgr}" == "apk" ]] && cmd="apk add $dep_apk"

    $cmd &> /dev/null
}

extract() {
    cd /tmp/ || exit
    mv micro-master.zip /tmp/target.zip
    mkdir /tmp/target

    unzip /tmp/target.zip -d /tmp/target/
    cd /tmp/target/micro-master/ || exit
}

compile() {
    make
}

inst() {
    echo -e "${Green}>>>${Reset}${Bold} Installing dependencies ... "
    get_dependencies

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

    echo -e "${Green}>>>${Reset}${Bold} Compiling ... "
    compile

    echo -e "${Green}>>>${Reset}${Bold} Installing nano ... "
    mv /tmp/target/micro-master/micro /usr/local/bin/micro
}

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

    echo -e "${Green}>>>${Reset}${Bold} Compiling ... "
    compile

    echo -e "${Green}>>>${Reset}${Bold} Installing nano ... "
    mv /tmp/target/micro-master/micro /usr/local/bin/micro
}

remove() {
    echo -e "${Green}>>>${Reset}${Bold} Removing nano ... "
    rm -f /usr/local/bin/micro
    read -rep $'\033[0;33m>>>\033[0m\e[1m Remove dependencies? [Y/N] ' ans

    if [[ "${ans}" != "y" ]] && [[ "${ans}" != "Y" ]] && [[ "${ans}" != "j" ]] && [[ "${ans}" != "j" ]]; then
        exit
    else 
        [[ "${pkg_mgr}" == "apt" ]] && cmd="apt remove -y $dep_apt"
        [[ "${pkg_mgr}" == "apk" ]] && cmd="apk remove $dep_apk"

        $cmd &> /dev/null
    fi
}

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