#!/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: ncmprhnsbl
# version: 20201210
#
# This is a script to update palemoon

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

txtbld=$(tput bold)
txtred=${txtbld}$(tput setaf 1)
txtgreen=${txtbld}$(tput setaf 2)
txtwhite=${txtbld}$(tput setaf 7)
txtcyan=${txtbld}$(tput setaf 6)
rst=$(tput sgr0)
function bold(){ echo -e $txtbld "$1" $rst; }
function green() { echo -e $txtgreen "$1" $rst; }
function red(){ echo $txtred "$1" $rst; }	
function cyan(){ echo $txtcyan "$1" $rst; }

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

# Check for root
if [ `whoami` != "root" ]; then
	echo "Only root can run this."
	exit 1
fi

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

set_pwd() {
WRKDIR=`pwd` 
}

# echo usage
show_help() {
	echo " options:  -d : do operations in the present 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

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

get_locale(){
# Set locales in array
for a in bg cs de el en-GB en-US es-AR es-ES es-MX fr hu it ko pl pt-BR pt-PT ru sk sv-SE tl tr uk vi zh-CN; do
	RESULT+=( $a )
done
array_menu "Choose a locale from the list." 
unset RESULT
}

# tell us where the work will be done
echo "Work will be done in: $WRKDIR "
 
## 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; }
}

# Check if palemoon is currently installed
bold "Checking if palemoon is installed ..."
command -pv palemoon >/dev/null && ISINSTALLED=0

# Get current palemoon version if installed
if [ "$ISINSTALLED" ]; then
	sayok "palemoon is installed"
	CVER=`palemoon --version | cut -d" " -f5` 
    [ "$CVER" ] ||  CVER=`ls /var/lib/pkgtools/packages/palemoon* | sort | tail -n1 | awk -F- '{print$2}'`
	[ "$CVER" ] && sayok "installed palemoon version: $txtgreen $CVER $rst" || echo "No palemoon version found"
		else
	echo "palemoon is not installed"
fi

# Set variables
#RELURL=http://linux.palemoon.org/download/mainline/
RELURL=https://www.palemoon.org/download.shtml
USE_SYSTEM_SPELLCHECK=yes
CWD=`pwd`
ARCH=${ARCH:-$(uname -m)}
SERVER=`awk -F= '/SERVER=/{print$NF}' /etc/porteus.conf`

case "$ARCH" in
  i?86) PARCH="i586" ; LIBDIRSUFFIX="" ; ARCH=i686 ;;
  x86_64) PARCH="x86_64" ; LIBDIRSUFFIX="64" ; ARCH=x86_64 ;;
  *) echo "Package for $(uname -m) architecture is not available." ; exit 1 ;;
esac
    
## Check for palemoon file in $WRKDIR
## If it exists then ask to build from it.
if [ `ls $WRKDIR/palemoon-* 2>/dev/null | wc -l` -ge 1 ]; then
	# Make sure it is a tarball(xz)
	cfile=( `ls -1 $WRKDIR/palemoon-*.xz 2>/dev/null | awk -F/ '{print$NF}'` )
	if [ ${#cfile[@]} -gt 0 ]; then
		RESULT=${cfile[@]}
		echo
		green "A palemoon tarball was found in $WRKDIR"
		echo " We will use this archive to create palemoon."
		menu_from_array "Choose the palemoon file you want to process."
		echo "CHOICE:$CHOICE"
		unset RESULT
	fi
fi

bold "Checking for Porteus ..."
is_porteus && saypass "Distro is Porteus" || { sayfail "Distro is not Porteus"; cleanup; }

if [ -z $CHOICE ]; then
	echo "Getting latest version ..."
	#VER=`wget release -q -O - $RELURL | sed -n '/<h3>/p' | head -1 | awk -F"<h3>" '{print$2}' | cut -d' ' -f1`
	#VER=`wget release -q -O - $RELURL | sed -n '/<h3>/p' | head -1 | awk -F"v" '{print$2}' | cut -d' ' -f1`
	#VER=`wget release -q -O - $RELURL | sed -n '/<h3>/p' | head -1 | awk -F"v" '{print$2}' | cut -d'"' -f1`
	#VER=`curl -sf $RELURL | grep 'Version:' | head -n1 | grep -o '[0-9]*\.[0-9]*' | sed 'N;s/\n//g'`
	#VER=`curl -sf $RELURL | grep 'Version:' | head -n1 | grep -o '[0-9]*\.[0-9]*' | tr -d '\n'`
	VER=`curl -sf $RELURL | grep linux-x86_64-gtk3 | grep -o '[0-9]*\.[0-9]' | tr -d '\n'`
	#VER=`curl -sf $RELURL | grep 'Version:' | head -n1 | grep -o '[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*'`
	if [ "$VER" ];then
			if [ "$VER" = "$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
			fi
	else
		sayerror "Could not find latest version"
		exit 1
	fi
fi

# Get version on porteus server
SERVER_LATFILE=`lynx -dump --nonumbers --listonly $SERVER/$PARCH/current/modules | awk -F/ '/palemoon/{print$NF}' | tail -n1`
SERVER_LATVER=`awk -F- '{print$2}' <<<$SERVER_LATFILE`

########## START FUNCTIONS
cleanup(){
[ -d $TMPDIR ] && rm -rf $TMPDIR
[ -d $PKG ] && rm -rf $PKG
exit	
}

create_default_homepage(){
echo "W0dsb2JhbF0KaWQ9UG9ydGV1cwp2ZXJzaW9uPTUuMAphYm91dD1QYWxlbW9vbiBmb3IgUG9ydGV1
cwoKW1ByZWZlcmVuY2VzXQphcHAudXBkYXRlLmF1dG89ZmFsc2UKYXBwLnVwZGF0ZS5lbmFibGVk
PWZhbHNlCmJyb3dzZXIuc3RhcnR1cC5ob21lcGFnZT0iZGF0YTp0ZXh0L3BsYWluLGJyb3dzZXIu
c3RhcnR1cC5ob21lcGFnZT1odHRwczovL2ZvcnVtLnBvcnRldXMub3JnLyIKYnJvd3Nlci5jYWNo
ZS5kaXNrLmNhcGFjaXR5PTEwMjQwCmJyb3dzZXIuc2hlbGwuY2hlY2tEZWZhdWx0QnJvd3Nlcj1m
YWxzZQo=" | base64 -d > $PKG/opt/palemoon/distribution/distribution.ini
}

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
}
# Generic checksum check
checksum () {
echo "Verifying download integrity.."
echo "Server  : $SUM1"
echo "Download: $SUM2"
if [ "$SUM1" = "$SUM2" ]; then 
     echo "Download verified." 
else 
	read -p "Integrity check failed. Would you like to continue anyway? [y/n]" -n 1 -r -s && echo
	if [[ $REPLY =~ ^[Nn]$ ]]; then
		cleanup
	fi
fi
}

trap cleanup SIGHUP SIGINT SIGTERM

if [ -z $CHOICE ]; then
	echo "Checking $SERVER/$PARCH/current/modules"
	echo
	if [ "$ARCH" = "i686" ];then
		red "Sorry, Palemoon no longer supplies 32bit binaries."
		cyan "If you want to use an older version go here:"
		bold "  https://www.palemoon.org/archived.shtml  "
		cyan "to find one, then place it in:"
		bold "$WRKDIR" 
		cyan "and rerun this script."
		cyan " or"
		cyan "You can choose to download the premade module from our server(en-US locale)"
		echo "The porteus server module version is:" $txtgreen "palemoon-$SERVER_LATVER" $rst
	else
		echo "The latest version is:" $txtgreen "palemoon-$VER" $rst
		echo "The porteus server module version is:" $txtgreen "palemoon-$SERVER_LATVER" $rst
		cyan "You can choose to download the premade module from our server(en-US locale)" 
		cyan "or download the version from palemoon.org,"  
		cyan "which enables you to choose your language and set a custom homepage."
	fi
	echo
	read -p " Would you like to download the porteus server module? [y/n]" -n 1 -r -s && echo
	if [[ $REPLY =~ ^[Yy]$ ]] ; then
		echo
		download $SERVER/$PARCH/current/modules/$SERVER_LATFILE $WRKDIR
		## Check that we have a module in $WRKDIR
        if [ ! -f $WRKDIR/$SERVER_LATFILE ]; then
			echo
			sayerror "Download of the palemoon module failed."
			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    
	elif [ "$ARCH" = "i686" ];then
		cleanup
	else
		check_space
		read -p " Would you like to create a module of the latest version? [y/n]" -n 1 -r -s && echo
		if [[ ! $REPLY =~ ^[Yy]$ ]]; then cleanup; fi
	fi
fi

get_home_page

if [ -z $CHOICE ]; then
	get_locale
fi

TMPDIR=$WRKDIR/.pale.$$
PRGNAM=palemoon
#BZ2URL=http://linux.palemoon.org/files/$VER/palemoon-$VER.en-US.linux-$ARCH.tar.bz2
#BZ2URL=http://linux.palemoon.org/datastore/release/palemoon-$VER.en-US.linux-$ARCH.tar.bz2
## note "tarball" is now tar.xz
#BZ2URL=http://linux.palemoon.org/datastore/release/palemoon-$VER.linux-$ARCH-gtk3.tar.xz
BZ2URL=https://rm-us.palemoon.org/release/palemoon-$VER.linux-$ARCH-gtk3.tar.xz
PFILE=${BZ2URL##*/}
PKG=$TMPDIR/package-$PRGNAM
OUTPUT=${OUTPUT:-$WRKDIR}
SERVER=`awk -F= '/SERVER=/{print$NF}' /etc/porteus.conf`

## Create temp dir
[ ! -d $TMPDIR ] && mkdir -p $TMPDIR || rm -rf $TMPDIR/*

## Download tarball
if [ -z $CHOICE ]; then
	if [ ! -e $WRKDIR/$PFILE ]; then
		download $BZ2URL $TMPDIR
	fi
else
	cp -a $WRKDIR/$CHOICE $TMPDIR
fi

## If locale other than en-US, fetch language pack
if [ -z $CHOICE ]; then
	if [ ! "$LOC" = "en-US" ]; then
		echo "Fetching language pack.."
		mkdir $TMPDIR/locale
		/usr/bin/curl --silent --user-agent 'PaleMoon' --output "$TMPDIR/locale/$PRGNAM-i18n-${LOC,,}-${VER}.xpi" "https://addons.palemoon.org/?component=download&version=${VER}&id=langpack-${LOC}@palemoon.org" && echo " Done." || echo "Language pack download failed!"
	fi
fi

## Check that we have an archive in TMPDIR
if [ -z $CHOICE ]; then 
	if [ ! -f $TMPDIR/$PFILE ]; then
		echo
		sayerror "File $PFILE not found"
		cleanup
	fi
elif [ ! -f $TMPDIR/$CHOICE ]; then
		echo
		sayerror "File $CHOICE not found"
		cleanup
fi


## Get and check checksum for tarball
if [ -z $CHOICE ]; then
	#SHAURL=http://linux.palemoon.org/download/mainline/
	if [ "$ARCH" = "x86_64" ]; then 
		LINE="head -n1" 
	else 
		LINE="tail -n1" 
	fi
fi
#SUM1=`wget release -q -O - $RELURL | sed -n '/SHA/p' | $LINE | cut -d" " -f6 | cut -d"<" -f1`
SUM1=`lynx -dump -dont_wrap_pre $RELURL | grep -A 1 linux-x86_64-gtk3 | tail -n1`
SUM2=`sha256sum $TMPDIR/$PRGNAM* | cut -d" " -f1`

if [ -z $CHOICE ]; then		
	checksum
fi

## Make the package and module
mkdir -p $PKG
cd $PKG
if [ -z $CHOICE ]; then
	tar xvf ../$PFILE || { red "Failed to decompress tarball."; exit 1; }
else 
	tar xvf ../$CHOICE || { red "Failed to decompress tarball."; exit 1; }
fi

chown -R root:root $PRGNAM
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 {} \;

# use system hunspell if user wants it
if [[ $USE_SYSTEM_SPELLCHECK == "yes" ]]; then
  rm -rf palemoon/dictionaries
  ln -sv /usr/share/hunspell $PRGNAM/dictionaries
fi

# create directories
mkdir -p $PKG/opt
mkdir -p $PKG/usr/bin
mkdir -p $PKG/usr/share/icons/hicolor/{16x16,32x32,48x48,128x128}/apps
mkdir -p $PKG/usr/share/applications
#mkdir -p $PKG/install

# install pale moon into /opt
cp -vr palemoon $PKG/opt
rm -rf palemoon

# create settings directory for distribution.ini for homepage setting
mkdir -p $PKG/opt/$PRGNAM/distribution

# link stuff
## binary
ln -s /opt/palemoon/palemoon $PKG/usr/bin/palemoon
## icons
ln -s /opt/palemoon/browser/chrome/icons/default/default16.png $PKG/usr/share/icons/hicolor/16x16/apps/palemoon.png
ln -s /opt/palemoon/browser/chrome/icons/default/default32.png $PKG/usr/share/icons/hicolor/32x32/apps/palemoon.png
ln -s /opt/palemoon/browser/chrome/icons/default/default48.png $PKG/usr/share/icons/hicolor/48x48/apps/palemoon.png
ln -s /opt/palemoon/browser/icons/mozicon128.png $PKG/usr/share/icons/hicolor/128x128/apps/palemoon.png


## Add distribution.ini to set homepage
echo "Setting Porteus Forum to Homepage"
create_default_homepage

# Add home page
echo "Adding home page ..."
sed -i 's@https://forum.porteus.org@'$HOMEPAGE'@g' $PKG/opt/$PRGNAM/distribution/distribution.ini

## Add language pack and set language if present
if [ -e "$TMPDIR/locale/$PRGNAM-i18n-${LOC,,}-${VER}.xpi" ]; then
	mkdir $PKG/opt/$PRGNAM/distribution/extensions
	cp $TMPDIR/locale/$PRGNAM-i18n-${LOC,,}-${VER}.xpi $PKG/opt/$PRGNAM/distribution/extensions/langpack-${LOC}@palemoon.org.xpi
	cat >> $PKG/opt/$PRGNAM/distribution/distribution.ini << EOF
general.useragent.locale="${LOC}"
extensions.autoDisableScopes=0
extensions.shownSelectionUI=true
intl.locale.matchOS=true
EOF
fi

## Install desktop file
cat > $PKG/usr/share/applications/$PRGNAM.desktop << EOF
[Desktop Entry]
Version=1.0
Name=Pale Moon Web Browser
Comment=Browse the World Wide Web
Keywords=Internet;WWW;Browser;Web;Explorer
Exec=palemoon %u
Terminal=false
X-MultipleArgs=false
Type=Application
Icon=palemoon
Categories=Network;WebBrowser;Internet;GTK;
MimeType=text/html;application/xhtml+xml;application/xml;application/rss+xml;application/rdf+xml;image/gif;image/jpeg;image/png;x-scheme-handler/http;x-scheme-handler/https;x-scheme-handler/ftp;x-scheme-handler/chrome;video/webm;application/x-xpinstall;
StartupNotify=true
EOF

cp -a $PKG/usr/share/applications/$PRGNAM.desktop $PKG/usr/share/applications/browser.desktop
echo "NoDisplay=true" >> $PKG/usr/share/applications/browser.desktop
sed -i 's/MimeType/#MimeType/' $PKG/usr/share/applications/browser.desktop

echo "Fixing permissions ..."
find $PKG -type d | xargs -i chmod 755 {}
find $PKG -type f | xargs -i chmod 644 {}
chmod +x $PKG/opt/palemoon/palemoon*

for a in `find $PKG -type f`; do
	if [[ `file $a | grep -o ELF` ]]||[[ `file $a | grep -o "shell"` ]]; then
		echo "Setting ${a##*/} as executable ..."
		chmod +x $a
	fi
done

if [ -d $PKG/home/guest ]; then echo "Setting guest permsissions ..."; chown -R guest: $PKG/home/guest; fi
chmod 755 $PKG/opt/palemoon/{plugin*,pale*,run*}


#echo "Copying config files ..."
#cp -a $CWD/files/* $PKG
#chown -R guest: $PKG/home/guest

find $PKG -print0 | xargs -0 file | grep -e "executable" -e "shared object" | grep ELF \
| cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null || true

## remove - for some locales
#~ if [ `echo $LOC | grep -` ]; then 
	#~ PLOC=${LOC/-/}
#~ else
	#~ PLOC=$LOC
#~ fi

if [ -z $CHOICE ]; then
	PNAME=$PRGNAM-$VER-$ARCH-${LOC}
else
	PNAME=${CHOICE::-7}
fi

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

cat >> $PKGINFO/$PNAME << EOM
PACKAGE DESCRIPTION:
palemoon: palemoon (Web browser)
palemoon:
palemoon: Pale Moon is a fork of pre-Australis Mozilla Firefox aiming to be
palemoon: fast, efficient and easy to use.
palemoon:
palemoon: Homepage: http://www.palemoon.org/
palemoon:
palemoon:
palemoon:
palemoon:
FILE LIST:
EOM

find * | grep -v var >> $PKGINFO/$PNAME
 
cd $WRKDIR


dir2xzm $PKG $OUTPUT/$PNAME.xzm
#/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VER-$ARCH-$PLOC.txz || { red "Failed to create slackware package."; exit 1; }
#txz2xzm $OUTPUT/$PRGNAM-$VER-$ARCH-$PLOC.txz || { red "Failed to create porteus module."; exit 1; }

echo
echo "Your file is at:" $txtcyan "$OUTPUT/$PNAME.xzm" $rst
echo "Please copy it to your modules folder to survive a reboot."
echo
cleanup

