#!/bin/bash

# Copyright 2016-2020  Jay Flood, SP, Brasil
# All rights reserved.
#
# 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.
#
# Author: brokenman@porteus.org
# mangled by: ncmprnhnsbl
# version : 20241205
# This is a script to update vivaldi

# Source porteus-functions
. /usr/share/porteus/porteus-functions
get_colors

# Check for root
SCRIPT="$(cd "${0%/*}" 2>/dev/null; echo "$PWD"/"${0##*/}")"
if [ `whoami` != "root" ]; then
	echo "This requires elevated privilege"
	exit
fi

# functions set work directory(default is /tmp) to current work directory
set_tmp() {
WRKDIR=/tmp 
}

set_pwd() {
echo $txtcyan " Please enter the path to the directory you want to use "
echo "  to do the file operations: " $rst
read WRKDIR
}

# echo usage
show_help() {
	echo " options:  -d : do operations in a chosen directory, instead of /tmp . "
	echo "           -h        : show this usage. "
}
while getopts ":-d:-h:" o; do
case "$1" in
 
    -d)
       set_pwd;;
    
    -h)
      show_help
      exit 0;;
              
     *)
      show_help
      exit 1;;
    
esac
done
case "$1" in
      
    "")
      set_tmp;;
      
esac

# tell us where the work will be done
echo "Work will be done in:" $txtgreen "$WRKDIR "$rst
 
## Check if there's enough working space
check_space() {
[ `df -l --output=avail $WRKDIR | tail -1` -lt 384000 ] && { red "There's not enough space to run this script"; exit 1; }
}

# Set variables
PKGNAM=vivaldi
#RELEASE=${RELEASE:-stable}    # stable, beta, or unstable
TMPDIR=$WRKDIR/portch
TARG=$TMPDIR/ch.$$
SERVER=`awk -F= '/SERVER=/{print$NF}' /etc/porteus.conf`
ARCH=${ARCH:-$(uname -m)}
CWD=`pwd`

case "$ARCH" in
  i?86) DEBARCH="i386" ; LIBDIRSUFFIX="" ; ARCH=i386 ; SARCH=i586 ; WARCH=ia32 ; PARCH=x86 ;;
  x86_64) DEBARCH="amd64" ; LIBDIRSUFFIX="64" ; ARCH=x86_64 ; SARCH=x86_64 ; WARCH=x64 ; PARCH=x64 ;;
  *) echo "Package for $(uname -m) architecture is not available." ; exit 1 ;;
esac

#RELEASEARRAY=( 'stable' 'unstable' 'beta' )
URL="https://downloads.vivaldi.com/stable/vivaldi-stable_$LVER_$DEBARCH.deb"

###### Functions
saypass(){ echo "[${txtbold}${txtgreen}PASS$rst] $1"; }
sayfail(){ echo "[${txtbold}${txtred}FAIL$rst] $1"; }

get_home_page(){
HOMEPAGE="https://forum.porteus.org"

bold "Set your home page."
echo " Leave blank for: https://forum.porteus.org and press Enter to continue."
read -p "> " answ

if [ `wc -c <<<$answ` -gt 1 ]; then
	HOMEPAGE=$answ
	unset answ
	echo "Verifying home page ..."
	if is_online_url $HOMEPAGE; then
		saypass "Homepage is online."
			else
		sayfail "This homepage is not available."
		echo
		$FUNCNAME
	fi
else
	saypass "Homepage is available"
fi
}

array_menu(){
echo
echo "$1"
echo "$2"
select CHOICE in ${RESULT[@]}; do
    if [ -z "$CHOICE" ]; then
        bold "English locale chosen." && echo
			else
		bold "$CHOICE locale chosen"
    fi
    break
done
}

get_locale(){
# Set locales in array
for a in de-CH de el en-GB en-US eo es-419 es-PE es et eu fa fi fil fr fy gd gl gu he hi hr hu hy id io is it ja-KS ja jbo ka kab kn ko ku lt lv mk ml mr ms nb nl nn pa pl pt-BR pt-PT ro ru sc sk sl sq sr-Latn sr sv sw ta te th tr uk ur vi zh-CN zh-TW; do
	RESULT+=( $a )
done

array_menu "Choose a locale from the list." "All other locales will be removed." ${RESULT[@]}
unset RESULT
}

cleanup(){
[ -d $TMPDIR ] && rm -rf $TMPDIR
[ -d $PKG ] && rm -rf $PKG
exit	
}
trap cleanup SIGHUP SIGINT SIGTERM
###### End of functions

# Get current vivaldi version if installed
command -pv vivaldi-stable >/dev/null 2>&1 || \
command -pv vivaldi >/dev/null 2>&1 && ISINSTALLED=0
if [ "$ISINSTALLED" ]; then
	CVER=`vivaldi-stable --version | awk '{print$2}'`
	[ "$CVER" ] && saypass "vivaldi ver: $CVER" || sayfail "No vivaldi version found"
		else
	echo "vivaldi is not installed"
fi

# Create TMPDIR
[ ! -d $TMPDIR ] && mkdir -p $TMPDIR

# Get link of widevine package from sBo
#SBURL=https://slackbuilds.org/slackbuilds/14.2/network/vivaldi/vivaldi.info
SBURL=https://slackware.uk/slackbuilds.org/14.2/network/vivaldi/vivaldi.info
GURL=https://dl.google.com/widevine-cdm/versions.txt
#WVURL=`lynx -dump -dont_wrap_pre $SBURL | grep widevine | grep $WARCH | awk '{print $1}' | tr -d '"'`
if [ $ARCH != "x86_64" ]; then 
	WVURL=`wget -q -O - $SBURL | grep widevine | grep $WARCH | awk '{print $1}' | tr -d '"'`
	WVER=`echo $WVURL | egrep -o "([0-9]{1,}\.)+[0-9]{1,}"`
else
	#~ WVURL1=`wget -q -O - $SBURL | grep widevine | awk '{print $1}' | tr -d '"'`
	#~ WVURL=`sed 's/ia32/x64/g' <<< $WVURL1`
	WVER=`wget -q -O - $GURL | tail -n 1`
	WURL=https://dl.google.com/widevine-cdm/$WVER-linux-x64.zip
fi
WVFL=`awk -F/ '{print $NF}' <<< $WVURL`
#WVER=`echo $WVURL | egrep -o "([0-9]{1,}\.)+[0-9]{1,}"`
#echo "widevine: $WVURL"
#echo "widevine: $WVFL"
 
# Get link of extra ffmpeg codecs from sBo
if [ $ARCH != "x86_64" ]; then
	FCURL=`wget -q -O - $SBURL | grep ffmpeg | grep $DEBARCH | awk '{print $1}'`
else
	FCURL=`wget -q -O - $SBURL | grep ffmpeg | grep $DEBARCH | awk '{print $NF}' | awk -F'"' '{print $1}'`
fi
FCDEB=`awk -F/ '{print $NF}' <<< $FCURL`
FCVER=`echo $FCURL | awk -F_ '{print $2}'`
#echo "codecs: $FCURL"
#echo "deb: $FCDEB"

# Get current vivaldi version online from AUR
echo
bold "Checking latest vivaldi version ..."
#wget --no-check-certificate ‐q -o $TMPDIR/log https://aur.archlinux.org/packages/vivaldi -P $TMPDIR/ver
wget -q -o $TMPDIR/log https://vivaldi.com/download/?platform=linux -P $TMPDIR/ver
if [ -e $TMPDIR/ver/index.html?platform=linux ]; then
	LVER=`grep "stable" $TMPDIR/ver/index.html?platform=linux | grep $DEBARCH | egrep -o "([0-9]{1,}\.)+[0-9]{1,}" | head -n 1`
	if [ "$LVER" = "$CVER" ]; then
		read -p " You already have the latest version $txtgreen$CVER$rst. Do you still want to continue? [y/n]" -n 1 -r -s && echo
			[[ $REPLY =~ ^[Nn]$ ]] && exit 0
	else
		[ "$LVER" ] && saypass "Latest ver: $LVER"
	fi
else
	sayerror "Failed to connect to vivaldi server."
	echo "We cannot continue."
	#cleanup
fi

## Check version on Porteus server
SERVER_LATFILE=`lynx -dump --nonumbers --listonly $SERVER/$SARCH/current/modules | awk -F/ '/vivaldi/{print$NF}' | tail -n1`
SERVER_LATVER=`awk -F- '{print$2}' <<<$SERVER_LATFILE`
echo
bold "Finished checks."
echo

######## Questions
echo
echo "#############################################"
echo "Welcome to the Porteus vivaldi updater."
echo
echo "Installed version: " $txtcyan "$CVER" $rst
echo "Porteus server version: " $txtcyan "$SERVER_LATVER" $rst
echo "Latest version: " $txtcyan "$LVER" $rst
echo

read -p " Would you like to download the porteus server version? [y/n]" -n 1 -r -s && echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
	download $SERVER/$SARCH/current/modules/$SERVER_LATFILE $WRKDIR
        ## Check that we have a module in $WRKDIR
        if [ ! -f $WRKDIR/$SERVER_LATFILE ]; then
	     echo
	     sayerror "Download of the vivaldi module failed."
	     echo
	     cleanup
        else
	    echo
	    echo "Your file is at:" $txtcyan "$WRKDIR/$SERVER_LATFILE" $rst
	    echo "Please move it to your modules folder to survive a reboot."
	    echo
	    cleanup
	fi
else
        check_space
		read -p " Would you like to create the module with the latest version? [y/n]" -n 1 -r -s && echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then cleanup; fi
fi

echo 
bold "Checking for required libs.."
echo	
# Check for libbfd
havebfd=`find /usr/ -name "libbfd*.so*"`
if [ -z "$havebfd" ]; then
	sayerror "No libbfd.so found"
	echo
	echo "This can be found in the binutils package or the 05-devel module."
	echo "So, either activate the 05-devel.xzm or "
	echo "type as root: ${txtcyan}getpkg binutils${rst}"
	echo "and activate the resulting module."
	echo "Then run ${txtcyan}update-vivaldi${rst} again."
	exit
		else
	sayok "libbfd was found"
fi
	
#get_home_page
get_locale
read -p " Would you like to create a Porteus module? [y/n]" -n 1 -r -s && echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
	cleanup
fi

echo "Downloading latest vivaldi ..."
### Download
if [ ! -f $WRKDIR/vivaldi-stable_$LVER_$DEBARCH.deb ]; then
    download "$URL" $TMPDIR
    DEB=$TMPDIR/vivaldi-stable_$LVER_$DEBARCH.deb
		else
	DEB=$WRKDIR/vivaldi-stable_$LVER_$DEBARCH.deb
fi

echo "Downloading widevine and extra codecs ..."
download $WVURL $TMPDIR
download $FCURL $TMPDIR

## Start of build

VERSION=$(ar p $DEB control.tar.gz 2> /dev/null | tar zxO ./control 2> /dev/null | grep Version | awk '{print $2}' | cut -d- -f1)
BUILD=${BUILD:-1}
PKG=$TMPDIR/package-$PKGNAM
OUTPUT=${OUTPUT:-$WRKDIR}

mkdir -p $PKG $OUTPUT
cd $PKG
ar vx $DEB data.tar.xz || { red "Failed to unpack deb file."; cleanup; }
tar xvf data.tar.xz
rm data.tar.xz

cd $TMPDIR
# Deal with extra codecs and widevine
echo "Adding extra codecs and widevine.."
if [ -e $TMPDIR/$FCDEB ]; then
	ar p $FCDEB data.tar.xz | tar xOJ ./usr/lib/chromium-browser/libffmpeg.so > $PKG/opt/vivaldi/libffmpeg.so.${FCVER%\.*\.*}
else
	echo "No extra codecs found.."
fi

if [ -e $TMPDIR/$WVFL ]; then
	rm -rf $PKG/opt/vivaldi/WidevineCdm
	if [ $ARCH = "x86_64" ]; then
		mkdir -p $PKG/opt/vivaldi/WidevineCdm
		unzip -oq $TMPDIR/$WVFL -d $PKG/opt/vivaldi/WidevineCdm
	else
		mkdir -p $PKG/opt/vivaldi/WidevineCdm/_platform_specific/linux_x86
		unzip -oq $TMPDIR/$WVFL -d $PKG/opt/vivaldi/WidevineCdm
		mv $PKG/opt/vivaldi/WidevineCdm/libwidevinecdm.so $PKG/opt/vivaldi/WidevineCdm/_platform_specific/linux_x86
	fi
else
	echo "No widevine found.."
fi

cd $PKG

chown -R root:root .
chmod -R u+w,go+r-w,a-s .
chmod 0755 .
#chmod 4711 opt/vivaldi/vivaldi/vivaldi-sandbox

# Remove locales
find opt/vivaldi/locales/ -name "*.pak" | egrep -v "fake-bidi|${CHOICE}.pak" | xargs -i rm {}
find opt/vivaldi/locales/ -name "*.pak.info" | egrep -v "fake-bidi|${CHOICE}.pak.info" | xargs -i rm {}
find opt/vivaldi/resources/vivaldi/default-bookmarks/ -name "*.json" | egrep -v "fake-bidi|${CHOICE}.json" | xargs -i rm {}
find opt/vivaldi/resources/vivaldi/_locales "*" | egrep -v "${CHOICE}" | xargs -i rm -rf {}
rm -rf etc

#mv $PKG/usr/share/man $PKG/usr/man
# Install a .desktop launcher:
sed -e "s|vivaldi-stable|vivaldi|" $PKG/usr/share/applications/vivaldi-stable.desktop > $PKG/usr/share/applications/vivaldi.desktop
rm $PKG/usr/share/applications/vivaldi-stable.desktop
sed -i -e "s#Icon=vivaldi#Icon=/opt/vivaldi/product_logo_256.png#" $PKG/usr/share/applications/vivaldi.desktop
cp -a $PKG/usr/share/applications/vivaldi.desktop $PKG/usr/share/applications/browser.desktop
sed -i '/Exec=/ a\NoDisplay=true' $PKG/usr/share/applications/browser.desktop
sed -i 's/MimeType/#MimeType/' $PKG/usr/share/applications/browser.desktop
#echo "NoDisplay=true" >> $PKG/usr/share/applications/browser.desktop
# strip some stuff
rm -rf $PKG/usr/share/{appdata,doc,gnome-control-center,menu,xfce4}
rm -r $PKG/opt/vivaldi/cron
# link the binary
mkdir $PKG/usr/bin
ln -sf /opt/vivaldi/vivaldi $PKG/usr/bin/vivaldi

# Create icon
[ ! -d $PKG/usr/share/pixmaps ] && mkdir -p $PKG/usr/share/pixmaps
chmod 755 $PKG/usr/share/pixmaps
ln -s /opt/vivaldi/product_logo_256.png $PKG/usr/share/pixmaps/vivaldi.png

## Install the user config files
#cp -a $CWD/files/* $PKG
#chown -R guest: $PKG/home/guest

cd $PKG

# Add home page
#sed -i 's/forum.porteus.org/'$HOMEPAGE'/g' $WRKDIR/un/home/guest/.config/vivaldi/Default/Preferences

# make the slackware package
#makepkg -l y -c n $OUTPUT/$PKGNAM-$LVER-$ARCH-${CHOICE}-$BUILD.txz || { red "Failed to create porteus module."; exit 1; }

### fake slackware type package info: super dumb version
PKGINFO=var/lib/pkgtools/packages
#FILES=`find *`
mkdir -p $PKGINFO
echo "PACKAGE NAME: $PRGNAM-$VER-$ARCH" > $PKGINFO/$PRGNAM-$VER-$ARCH

cat >> $PKGINFO/$PRGNAM-$LVER-$ARCH << EOM
PACKAGE DESCRIPTION:
vivaldi: Vivaldi (vivaldi web browser)
vivaldi:
vivaldi: vivaldi is an advanced browser made with the power user in mind.
vivaldi:
vivaldi:
vivaldi:
vivaldi:
vivaldi:
vivaldi: Homepage:  http://www.vivaldi.com
vivaldi:
FILE LIST:
EOM

find * | grep -v var >> $PKGINFO/$PRGNAM-$LVER-$ARCH
# make the module
#~ if [ "$MAKEMOD" ]; then
	#~ bold "Creating Porteus module ..."
	#~ txz2xzm $OUTPUT/$PKGNAM-$LVER-$ARCH-${CHOICE}-$BUILD.txz || { red "Failed to create porteus module."; exit 1; }
#~ fi
cd $WRKDIR && dir2xzm $PKG $OUTPUT/$PKGNAM-$LVER-$ARCH-${CHOICE}-$BUILD.xzm
# fix permissions
#chmod 644 $OUTPUT/$PKGNAM-$LVER-$ARCH-${CHOICE}-$BUILD.xzm

echo
echo "Your file is at:" $txtcyan "$OUTPUT/$PKGNAM-$LVER-$ARCH-${CHOICE}-$BUILD.xzm" $rst
echo "Please move it to your modules folder to survive a reboot."
echo
cleanup
