#!/bin/bash

# 2022 Paulo Bettega
# Este script SlackBuild descompacta o pacote Debian GBPCEFwr(64|32).deb usado
# no internet banking da CEF-Caixa Econômica Federal, e faz um pacote para ser
# instalado no Slackware 15.0 (versão estável) e Slackware -current (versão de
# desenvolvimento).
#
# Link para o Slackware 15.0:
# http://www.slackware.com/
#
# Link para o Slackware -current:
# https://slackware.nl/slackware/slackware-current-iso/
# https://slackware.nl/slackware/slackware64-current-iso/
# (novos isos são criados automaticamente quando há mudanças no ChangeLog,
#  as mudanças são quase sempre diárias
# https://ftp.osuosl.org/pub/slackware/slackware{64}-current/ChangeLog.txt)
#
# Para executar este script: o script deve estar no mesmo diretório que o
# pacote Debian GBPCEFwr(64|32).deb. O pacote de instalação será criado no
# diretório /tmp (default para $OUTPUT).
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.



cd $(dirname $0) ; CWD=$(pwd)

# GBPCEFwr é o nome do pacote Debian. Poderia ser algum outro como "warsaw".
PRGNAM=GBPCEFwr
# É melhor não haver hífen no número de versão.
VERSION=${VERSION:-2.21.1_13}
BUILD=${BUILD:-1}
# Tag é a identificação do autor do script slackbuild, tem que ser alguma coisa.
# Apenas os pacotes originais do Slackware não tem tag no nome.
TAG=${TAG:-phfb}
PKGTYPE=${PKGTYPE:-txz}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i586 ;;
    arm*) ARCH=arm ;;
    # Unless $ARCH is already set, use uname -m for all other archs:
       *) ARCH=$( uname -m ) ;;
  esac
fi

# Arquitetura do pacote Debian de acordo com $ARCH.
case "$ARCH" in
	  i586) DEB_ARCH=32	;;
	x86_64) DEB_ARCH=64	;;
esac

# If the variable PRINT_PACKAGE_NAME is set, then this script will report what
# the name of the created package would be, and then exit. This information
# could be useful to other scripts.
if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
  echo "$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE"
  exit 0
fi

TMP=${TMP:-/tmp/SBo}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

set -e

rm -rf "$PKG"
mkdir -p "$TMP" "$PKG" "$OUTPUT"
cd "$TMP"
rm -rf "$PRGNAM-$VERSION"
mkdir "$PRGNAM-$VERSION"
cd "$PRGNAM-$VERSION"
ar x "$CWD"/GBPCEFwr"$DEB_ARCH".deb
tar xvf data.tar.?z -C "$PKG"
# Backup dos arquivos relacionados ao Debian.
# O warsaw parece rodar sem problemas no Slackware sem esses arquivos.
mkdir "$PKG"/usr/share/doc/warsaw/debian-files
tar xvf control.tar.?z -C "$PKG"/usr/share/doc/warsaw/debian-files
cp -r "$PKG"/etc "$PKG"/lib "$PKG"/usr/share/doc/warsaw/debian-files
rm -r "$PKG"/etc/init "$PKG"/etc/init.d/warsaw "$PKG"/lib
gunzip "$PKG"/usr/share/doc/warsaw/changelog.Debian.gz

mkdir -p "$PKG"/etc/rc.d/{rc{0,1,2,3,4,5,6},init}.d
# Arquivo de inicialização no boot.
cat <<'EOF' > "$PKG"/etc/rc.d/init.d/warsaw
#!/bin/sh
#
# /etc/rc.d/init.d/warsaw start|stop|restart|status
#
# Start/Stop/Restart/Status warsaw daemon.
#
# Provides: /usr/local/bin/warsaw/core
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: Warsaw provides the needed software to use some banking services of popular financial organizations in South America. Topaz OFD Desktop https://www.topaz.com.br/ofd/contato-antifraude.php
 

# pid usado nas funções status e stop.
core_pid_arq=$(cat /var/run/core.pid 2>/dev/null)
core_pid_pgrep=$(pgrep -u root -f /usr/local/bin/warsaw/core)


start(){
	echo "Starting CEF internet banking software: /usr/bin/warsaw"
	/usr/bin/warsaw start
}

status(){
	if [ ! -z "$core_pid_pgrep" ]; then
	    echo /usr/bin/warsaw is running for root
	else
	    echo /usr/bin/warsaw is not running for root
	fi

	if [ "$USER" = root ]; then
	    ps aux|awk '/warsaw/ {
		if ( !/awk|^root/ ) print "/usr/bin/warsaw is running for "$1
		}'
	fi
		
	if [ "$USER" != root ]; then
	    if pgrep -u "$USER" -f /usr/local/bin/warsaw/core >/dev/null; then
		echo /usr/bin/warsaw is running for "$USER"
	    else
		echo /usr/bin/warsaw is not running for "$USER"
	    fi
	fi
}

stop(){

	echo "Stoping CEF internet banking software: /usr/bin/warsaw"
	/usr/bin/warsaw stop

	# "/usr/bin/warsaw stop" encerra todos os processos
	# /usr/local/bin/warsaw/core do root e dos usuários, mas não remove
	# o arquivo com o pid "/var/run/core.pid" (além disso, também não
	# encerra o processo /usr/local/bin/warsaw/wsatspi para os usuários,
	# que algumas vezes é iniciado, outras não).
	#
	# core.pid é talvez um nome muito genérico, seria melhor se fosse
	# warsaw-core.pid para o root, e warsaw-core-$USER.pid e
	# warsaw-wsatspi-$USER.pid para os processos dos usuários.
	#
	# Tenha certeza que o arquivo /var/run/core.pid se refere realmente
	# ao processo /usr/loca/bin/warsaw/core antes de remover o arquivo.
	if [ "$core_pid_arq" = "$core_pid_pgrep" ]; then
		rm -f /var/run/core.pid 2>/dev/null
	fi

	# Garanta que nenhum processo warsaw ficou pendente.
	# (algumas vezes o processo /usr/local/bin/warsaw/wsatspi -apenas para
	#  os usuários, nunca vi esse processo rodando como root- é iniciado
	#  e não é encerrado).
	sleep 1
	if ps aux|grep -q /usr/local/bin/warsaw|grep -v grep; then
	    for i in /usr/local/bin/warsaw/*; do
		pkill -f /usr/local/bin/warsaw/$i 2>/dev/null
	    done
	fi
	sleep 1
	if ps aux|grep -q /usr/local/bin/warsaw|grep -v grep; then
	    for i in /usr/local/bin/warsaw/*; do
		pkill -9 -f /usr/local/bin/warsaw/$i 2>/dev/null
	    done
	fi
}

case "$1" in
	start) start
	;;

	stop) stop
	;;

	status) status
	;;

	restart) stop; sleep 1; start
	;;


	*)echo "Usage: $0 start|stop|restart|status"
esac
EOF

chmod +x "$PKG"/etc/rc.d/init.d/warsaw

mkdir -p "$PKG"/etc/xdg/autostart
# Arquivo de inicialização na interface gráfica. Com a opção "Hidden=true", a
# idéia é que cada usuário habilite o serviço por conta própria.
cat <<'EOF' > "$PKG"/etc/xdg/autostart/warsaw.desktop
[Desktop Entry]
Encoding=UTF-8
Version=2.21.1-13
Type=Application
Name=GBPCEFwr warsaw
Comment=CEF internet banking software.
Icon=
Exec=/etc/rc.d/init.d/warsaw start
OnlyShowIn=
RunHook=0
StartupNotify=false
Terminal=false
Hidden=true
EOF

chown -R root:root .
find -L . \
 \( -perm 777 -o -perm 775 -o -perm 750 -o -perm 711 -o -perm 555 \
  -o -perm 511 \) -exec chmod 755 {} \; -o \
 \( -perm 666 -o -perm 664 -o -perm 640 -o -perm 600 -o -perm 444 \
  -o -perm 440 -o -perm 400 \) -exec chmod 644 {} \;

cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/share/doc/warsaw/$PRGNAM.SlackBuild

mkdir -p "$PKG"/install
# Arquivo "install/slack-desc", contém informação sobre o pacote mostrada
# na instalação, e fica disponível no arquivo de registro da instalação em
# "/var/lib/pkgtools/packages/<nome do pacote>".
cat <<'EOF' > "$PKG"/install/slack-desc
# HOW TO EDIT THIS FILE:
# The "handy ruler" below makes it easier to edit a package description.  Line
# up the first '|' above the ':' following the base package name, and the '|'
# on the right side marks the last column you can put a character in.  You must
# make exactly 11 lines for the formatting to be correct.  It's also
# customary to leave one space after the ':'.

        |-----handy-ruler------------------------------------------------------|
GBPCEFwr: GBPCEFwr (needed software to run some banking services)
GBPCEFwr:
GBPCEFwr: Warsaw provides the needed software to use some banking services,
GBPCEFwr: will easily add the required software to let you use some of the
GBPCEFwr: internet banking services of popular financial organizations
GBPCEFwr: in South America. If you are unsure if you need this package
GBPCEFwr: please call your service desk and ask them for instructions.
GBPCEFwr: Version: 2.21.1-13
GBPCEFwr: Topaz OFD Desktop https://www.topaz.com.br/ofd/contato-antifraude.php
GBPCEFwr: Depends: libdbus-1-3, procps, zenity, python3
GBPCEFwr: Suggests: python3-gpgme | python3-gpg
EOF

# Arquivo "install/doinst.sh", executa comandos necessários na instalação.
# Cria os links "start" e "kill" para cada runlevel.
cat <<'EOF' > "$PKG"/install/doinst.sh
( cd etc/rc.d/rc0.d ; rm -rf Kwarsaw )
( cd etc/rc.d/rc0.d ; ln -sf /etc/rc.d/init.d/warsaw Kwarsaw )
( cd etc/rc.d/rc1.d ; rm -rf Kwarsaw )
( cd etc/rc.d/rc1.d ; ln -sf /etc/rc.d/init.d/warsaw Kwarsaw )
( cd etc/rc.d/rc2.d ; rm -rf Swarsaw )
( cd etc/rc.d/rc2.d ; ln -sf /etc/rc.d/init.d/warsaw Swarsaw )
( cd etc/rc.d/rc3.d ; rm -rf Swarsaw )
( cd etc/rc.d/rc3.d ; ln -sf /etc/rc.d/init.d/warsaw Swarsaw )
( cd etc/rc.d/rc4.d ; rm -rf Swarsaw )
( cd etc/rc.d/rc4.d ; ln -sf /etc/rc.d/init.d/warsaw Swarsaw )
( cd etc/rc.d/rc5.d ; rm -rf Swarsaw )
( cd etc/rc.d/rc5.d ; ln -sf /etc/rc.d/init.d/warsaw Swarsaw )
( cd etc/rc.d/rc6.d ; rm -rf Kwarsaw )
( cd etc/rc.d/rc6.d ; ln -sf /etc/rc.d/init.d/warsaw Kwarsaw )
EOF

mkdir -p "$PKG"/var/lib/pkgtools/douninst.sh
# Arquivo "/var/lib/pkgtools/douninst.sh/<nome do pacote>", executa comandos
# necessários na desinstalação.
# Algumas vezes os processos warsaw ficam em execução se o pacote for
# desinstalado sem executar "/usr/bin/warsaw stop" antes.
cat <<'EOF' > "$PKG"/var/lib/pkgtools/douninst.sh/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG
pkill -f /usr/local/bin/warsaw/core 2>/dev/null
pkill wsatspi 2>/dev/null
sleep 2
pkill -9 -f /usr/local/bin/warsaw/core 2>/dev/null
pkill -9 wsatspi 2>/dev/null
EOF
chmod +x "$PKG"/var/lib/pkgtools/douninst.sh/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG

cd "$PKG"
/sbin/makepkg -l y -c n "$OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE"
