#!/bin/sh

APP=freac

# CREATE THE FOLDER
mkdir /opt/$APP
cd /opt/$APP

# ADD THE REMOVER
echo '#!/bin/sh' >> /opt/$APP/remove
echo "rm -R -f /usr/local/share/applications/$APP-AM.desktop /opt/$APP /usr/local/bin/$APP" >> /opt/$APP/remove
chmod a+x /opt/$APP/remove

# DOWNLOAD THE APPIMAGE
mkdir tmp
cd ./tmp

wget https://github.com/$(wget https://github.com/enzo1982/freac/releases/latest | grep -E '/.*/.*/.*aarch64.AppImage' -o);

version=$(ls /opt/$APP/tmp)
echo "$version" >> /opt/$APP/version

cd ..
mv ./tmp/*mage ./$APP
chmod a+x /opt/$APP/$APP
rmdir ./tmp

# LINK
ln -s /opt/$APP/$APP /usr/local/bin/$APP

# SCRIPT TO UPDATE THE PROGRAM
echo '#!/bin/sh' >> /opt/$APP/AM-updater
echo "APP=$APP" >> /opt/$APP/AM-updater
echo "cd /opt/$APP" /usr/local/bin/$APP
echo 'version0=$(cat /opt/$APP/version)

url=https://github.com/enzo1982/freac/releases/latest' >> /opt/$APP/AM-updater

echo 'if curl -L -s $url | grep -ioF "$version0"; then' >> /opt/$APP/AM-updater
echo '  echo "Update not needed!".'  >> /opt/$APP/AM-updater
echo 'else' >> /opt/$APP/AM-updater
echo "  notify-send 'A new version of $APP is available, please wait'" >> /opt/$APP/AM-updater
echo "  mkdir /opt/$APP/tmp
  cd /opt/$APP/tmp" >> /opt/$APP/AM-updater

########################################################################################

function1='$(wget https://github.com/enzo1982/freac/releases/latest -O -'
function2="grep -E '/.*/.*/.*aarch64.AppImage' -o)"
function3='$(ls /opt/$APP/tmp)'

echo "  wget https://github.com/$function1 | $function2
  version=$function3" >> /opt/$APP/AM-updater

########################################################################################

echo '  cd ..
  if test -f ./tmp/*mage; then rm ./version
  fi
  echo "$version" >> ./version' >> /opt/$APP/AM-updater
echo "  mv ./tmp/*mage ./$APP
  chmod a+x /opt/$APP/$APP
  rmdir ./tmp
fi" >> /opt/$APP/AM-updater
chmod a+x /opt/$APP/AM-updater

# LAUNCHER
rm -f /usr/local/share/applications/$APP-AM.desktop
echo "[Desktop Entry]
Name=fre:ac
Comment=A free audio converter
Exec=freac %F
Type=Application
Icon=/opt/$APP/$APP.svg
Categories=AudioVideo;Audio;
Keywords=freac;
MimeType=x-content/audio-cdda;application/x-cue;audio/aac;audio/flac;audio/mpeg;audio/mp2;audio/mp4;audio/x-m4b;audio/ogg;audio/x-flac+ogg;audio/x-opus+ogg;audio/x-speex+ogg;audio/x-vorbis+ogg;audio/x-ape;audio/x-musepack;audio/x-wavpack;audio/x-ms-wma;audio/x-aiff;audio/x-voc;audio/x-wav;" >> /usr/local/share/applications/$APP-AM.desktop

# ICON
wget https://raw.githubusercontent.com/ivan-hc/AM-application-manager/main/programs/.icons/$APP/$APP.svg
