#!/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 : 20201128

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

# 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

# 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; }
}

ARCH=`uname -m`
case "$ARCH" in
  i?86) ARCH="i386" ; LIBDIRSUFFIX=""; MARCH=i586; OARCH=i386 ;;
  x86_64) ARCH="amd64" ; LIBDIRSUFFIX="64" ; MARCH=x86_64; OARCH=x86_64 ;;
  *) echo "Package for $(uname -m) architecture is not available." ; exit 1 ;;
esac

TMPDIR=$WRKDIR/opera.$$
# Function to check if gsettings-desktop-schemas is currently installed
check_gsettings(){
echo "Checking if gsettings is installed ..."
ls /usr/share/glib-2.0/schemas/org.gnome.desktop.background.gschema.xml >/dev/null 2>&1 && GSET=0
if [ "$GSET" ]; then
	sayok "gsettings-desktop-schemas is installed, you're good to go"
		else
	sayerror " Package: gsetting-desktop-schemas is not installed."
	echo     " Opera requires this for it's settings. " 
	echo     " Please try command: ${txtgreen}getpkg gsetting-desktop-schemas${rst} "
fi
}

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

# Get current opera version if installed
if [ "$ISINSTALLED" ]; then
	sayok "opera is installed"
	CVER=`opera --version | awk '{print$NF}'`
	[ "$CVER" ] && sayok "opera version: $CVER" || echo "No opera version found"
		else
	echo " opera is not installed"
fi

echo "Getting version information...please wait."
##get latest versions
URL="https://deb.opera.com/opera/pool/non-free/o"
OP1="opera-stable"
OP2="opera-beta"
OP3="opera-developer"

OSERVER1=$URL/$OP1
OSERVER2=$URL/$OP2
OSERVER3=$URL/$OP3

DL1=`lynx -dump --nonumbers --listonly  $OSERVER1 | grep "$ARCH"` 
DL2=`lynx -dump --nonumbers --listonly  $OSERVER2 | grep "$ARCH"` 
DL3=`lynx -dump --nonumbers --listonly  $OSERVER3 | grep "$ARCH"` 

LATVER1=`lynx -dump --nonumbers --listonly  $OSERVER1 | grep "$ARCH"| awk -F/ '{print $(NF)}' | awk -F_ '{print$2}'`
LATVER2=`lynx -dump --nonumbers --listonly  $OSERVER2 | grep "$ARCH"| awk -F/ '{print $(NF)}' | awk -F_ '{print$2}'`
LATVER3=`lynx -dump --nonumbers --listonly  $OSERVER3 | grep "$ARCH"| awk -F/ '{print $(NF)}' | awk -F_ '{print$2}'`

CKURL=https://deb.opera.com/opera/dists/stable/non-free/binary-$ARCH/Packages
SUMS=`lynx -dump -dont_wrap_pre $CKURL | sed -n '/SHA256/p' | cut -d" " -f2 | tail -n 1`
SUMB=`lynx -dump -dont_wrap_pre $CKURL | sed -n '/SHA256/p' | cut -d" " -f2 | head -n 2 | tail -n 1`
SUMD=`lynx -dump -dont_wrap_pre $CKURL | sed -n '/SHA256/p' | cut -d" " -f2 | head -n 3 | tail -n 1`
###### Functions
cleanup(){
rm -rf $TMPDIR 2>/dev/null
exit 0	
}
trap cleanup SIGHUP SIGINT SIGTERM

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

bold "Set your home page then press enter."
echo " Leave blank for: https://forum.porteus.org"
read -p "> " answ

if [ `wc -c <<<$answ` -gt 1 ]; then
	HOMEPAGE=$answ
	unset answ
	echo "Verifying home page ..."
	if is_online_url $HOMEPAGE; then
		sayok "Homepage is online."
			else
		sayerror "This homepage is not available."
		echo
		$FUNCNAME
	fi
else
	sayok "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"
		echo
    fi
    break
done
}

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

get_release_type(){
array_menu2 "Please choose a release from the menu." "Stable is recommended." $RESULT

case $CHOICE in
	stable) OP=opera-stable; RVERS=$LATVER1; DL=$DL1; LPATH=opera; SUM1=$SUMS ;;
	beta) OP=opera-beta; RVERS=$LATVER2; DL=$DL2; LPATH=opera-beta; SUM1=$SUMB ;;
	developer) OP=opera-developer; RVERS=$LATVER3; DL=$DL3; LPATH=opera-developer; SUM1=$SUMD ;;
	*)
	echo "Invalid choice"
	$FUNCNAME
	;;
esac
}

## checksum check
checksum () {
echo "Verifying download integrity.."
echo "Server  : $SUM1"
echo "Download: $SUM2"
if [ "$SUM1" = "$SUM2" ]; then 
     echo "Download verified." 
else 
     echo "Integrity check failed."
     cleanup 
fi
}

# Get the porteus server version

SERVER=`awk -F"=" '/SERVER=/{print$NF}' /etc/porteus.conf`
SERVER_LATFILE=`lynx -dump $SERVER/$MARCH/current/modules | awk -F/ '/opera/{print$NF}' | tail -n1`
#SERVER_LATVER=`awk -F- '{print $1-$3}' <<<$SERVER_LATFILE`
SERVER_LATVER=`cut -d"-" -f2-3  <<<$SERVER_LATFILE`
# check installed version is up to date, if so offer escape.
if [ "$LATVER1" = "$CVER" ]; then
	read -p " You already have the latest $OP1 version $txtgreen$CVER$rst. Do you still want to continue? [y/n]" -n 1 -r -s && echo
        [[ $REPLY =~ ^[Nn]$ ]] && exit 0
fi
if [ "$LATVER2" = "$CVER" ]; then
	read -p " You already have the latest $OP2 version $txtgreen$CVER$rst. Do you still want to continue? [y/n]" -n 1 -r -s && echo
        [[ $REPLY =~ ^[Nn]$ ]] && exit 0
fi
if [ "$LATVER3" = "$CVER" ]; then
	read -p " You already have the latest $OP3 version $txtgreen$CVER$rst. Do you still want to continue? [y/n]" -n 1 -r -s && echo
        [[ $REPLY =~ ^[Nn]$ ]] && exit 0
fi

echo "The porteus server version is : ${txtbld}${txtgreen}${SERVER_LATVER}${rst}"
echo "The opera-stable version is   : ${txtbld}${txtgreen}${LATVER1}${rst}"
echo "The opera-beta version is     : ${txtbld}${txtgreen}${LATVER2}${rst}"
echo "The opera-developer version is: ${txtbld}${txtgreen}${LATVER3}${rst}"
echo
echo $txtcyan"You can choose to download the premade module from our server(en-US locale) 
or download one of the versions from the opera server, which enables you to choose your language."$rst
read -p " Would you like to download the porteus server version? [y/n]" -n 1 -r -s && echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
	echo
	download $SERVER/$MARCH/current/modules/$SERVER_LATFILE $WRKDIR
        ## Check that we have a module in $WRKDIR
        if [ ! -f $WRKDIR/$SERVER_LATFILE ]; then
	     echo
	     sayerror "Download of the opera 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
	    check_gsettings
	    cleanup
	fi
fi
	
########## Begin input
echo
RESULT+=( 'stable' 'beta' 'developer' )
get_release_type
#URL="https://deb.opera.com/opera/pool/non-free/o"
#OSERVER=$URL/$OP

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

# Download the index file
#echo " Getting version info..."
#wget $OSERVER -P $TMPDIR 2>&1 | grep --line-buffered "%" |sed -u -e "s,\.,,g" | awk '{printf("\b\b\b\b%4s", $2)}'
#echo -ne "\b\b\b\b"

# Get the version
#RFILE=`grep -Po '".*?deb"' $TMPDIR/$OP | sed 's/.*"\(.*\)"[^"]*$/\1/' | grep "$ARCH"`
RFILE="${OP}_${RVERS}_${ARCH}.deb"
#RVER=`awk -F_ '{print$2}' <<<$RFILE`

# Ask user to download
#echo "The current $OP version is: ${txtbld}${txtgreen}${RVERS}${rst}"

read -p " Would you like to create the module of ${txtbld}${txtgreen}${OP}-${RVERS}${rst} ? [y/n]" -n 1 -r -s && echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then cleanup; fi
unset answ
echo "__________________________________"

check_space
	
echo
bold "Checking for required tools.."
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-opera${rst} again."
	exit 1
		else
	sayok "libbfd was found"
fi

# Check for libfl.so.2
havelibfl=`find /usr -name "libfl.so.*"`
if [ -z "$havelibfl" ]; then
	sayerror "No libfl.so.2 found"
	echo
	echo "This can be found in the flex package or the 05-devel module."
	echo "So, either activate the 05-devel.xzm or "
	echo "type as root: ${txtcyan}getpkg flex${rst}"
	echo "and activate the resulting module."
	echo "Then run ${txtcyan}update-opera${rst} again."
	exit 1
		else
	sayok "libfl was found"
fi
	
# Check for ar
if [ `command -pv ar` ]; then
	sayok "ar command found"
		else
	sayerror "No command ar 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-opera${rst} again."
	exit 1
fi

# Choose locale
RESULT=( af az be bg bn ca cs da de el en-GB en-US es-419 es fi fil fr-CA fr fy gd he hi hr hu id it ja kk ko lt lv me mk ms nb nl nn pa pl pt-BR pt-PT ro ru sk sr sv sw ta te th tr uk uz vi zh-CN zh-TW zu )
CTXT=`bold "Choose a language from the list."`
array_menu "$CTXT" " The others will be removed from the package. " $RESULT

# Get link
#LINK=$OSERVER/$RFILE

# Download it
if [ ! -e $WRKDIR/$RFILE ]; then
	download $DL $TMPDIR
		else
	cp -a $WRKDIR/$RFILE $TMPDIR
fi

## Check that we have an archive in TMPDIR
if [ ! -f $TMPDIR/$RFILE ]; then
	echo
	sayerror "File $TMPDIR/$RFILE not found"
	cleanup
fi
## Check the checksum
SUM2=`sha256sum $TMPDIR/$RFILE | cut -d" " -f1`

checksum

mkdir $TMPDIR/build
cd $TMPDIR/build
dataname=`ar t ../$RFILE | grep data`

case $dataname in
data.tar.gz)
echo "Running primary decompression ..."
/usr/bin/ar x ../$RFILE data.tar.gz
mv data.tar.gz opera-$RVER-$MARCH-1.tgz
;;
data.tar.lzma)
/usr/bin/ar x ../$RFILE data.tar.lzma
echo "Running primary decompression ..."
unxz data.tar.lzma
echo "Running secondary decompression ..."
gzip data.tar
mv data.tar.gz opera-$RVER-$MARCH-1.tgz
;;
data.tar.xz)
/usr/bin/ar x ../$RFILE data.tar.xz
echo "Running primary decompression ..."
unxz data.tar.xz
echo "Running secondary decompression ..."
gzip data.tar
mv data.tar.gz opera-$RVERS-$MARCH-1.tgz
;;
esac

explodepkg opera-$RVERS-$MARCH-1.tgz
rm opera-$RVERS-$MARCH-1.tgz

DTOP=usr/share/applications/*.desktop
sed -i 's/Icon=.*/Icon=opera/g' $DTOP
cp -a $DTOP usr/share/applications/browser.desktop
echo "" >> usr/share/applications/browser.desktop
echo "NoDisplay=true" >> usr/share/applications/browser.desktop
sed -i 's/MimeType/#MimeType/' usr/share/applications/browser.desktop
sed -i '/Target/d' usr/share/applications/browser.desktop
rm -rf usr/share/doc/*
#mkdir install

### fake slackware type package info: super dumb version
PKGINFO=var/lib/pkgtools/packages
#FILES=`find *`
mkdir -p $PKGINFO
echo "PACKAGE NAME: ${OP}-${RVERS}-$MARCH-$CHOICE-1" > $PKGINFO/${OP}-${RVERS}-$MARCH-$CHOICE-1
cat >> $PKGINFO/${OP}-${RVERS}-$MARCH-$CHOICE-1 << EOF
PACKAGE DESCRIPTION:
opera-next: opera-next (Fast and secure web browser and Internet suite)
opera-next:
opera-next: Opera is a small, fast, customizable, powerful, and user-friendly web
opera-next: browser, as well as an Internet suite, including an email client, an
opera-next: IRC client, web developer tools (opera-next Dragonfly).
opera-next:
opera-next: http://www.opera.com/browser/
opera-next:
opera-next:
opera-next:
opera-next:
FILE LIST:
EOF

find * | grep -v var >> $PKGINFO/${OP}-${RVERS}-$MARCH-$CHOICE-1

#~ cat > install/doinst.sh << EOM
#~ if [ -x /usr/bin/update-desktop-database ]; then
  #~ /usr/bin/update-desktop-database -q usr/share/applications >/dev/null 2>&1
#~ fi

#~ if [ -x /usr/bin/update-mime-database ]; then
  #~ /usr/bin/update-mime-database usr/share/mime >/dev/null 2>&1
#~ fi

#~ if [ -e usr/share/icons/hicolor/icon-theme.cache ]; then
  #~ if [ -x /usr/bin/gtk-update-icon-cache ]; then
    #~ /usr/bin/gtk-update-icon-cache usr/share/icons/hicolor >/dev/null 2>&1
  #~ fi
#~ fi
#~ EOM

case $OP in
	opera)
	echo "Removing locales ..."
	echo $CHOICE | grep -qo "^en-US" && CHOICE=en
	find usr/share/opera/locale/ -maxdepth 1 -type d | sed '1d' | grep -v "/$CHOICE$" | xargs -i rm -r {}
	;;
	opera-stable)
	chmod 4755 usr/lib/$OARCH-linux-gnu/$LPATH/opera_sandbox
	ln -sf /usr/lib/$OARCH-linux-gnu/$LPATH/$LPATH usr/bin/opera
	for a in `find usr/share/ -name "*.png" | grep $OP`; do pth=${a%/*}; nam=opera.png; mv $a $pth/$nam; done
	ODIR=`find usr/ -type d -name opera`
	LDIR=`find usr/ -type d -name localization`
	find $LDIR -name "*.pak" | egrep -v "fil.pak|$CHOICE|en-US" | xargs -i rm {}
	;;
	opera-beta)
	chmod 4755 usr/lib/$OARCH-linux-gnu/$LPATH/opera_sandbox
	ln -sf /usr/lib/$OARCH-linux-gnu/$LPATH/$LPATH usr/bin/opera
	LDIR=`find usr/ -type d -name localization`
	find $LDIR -name "*.pak" | egrep -v "fil.pak|$CHOICE|en-US" | xargs -i rm {}
	;;
	opera-developer)
	chmod 4755 usr/lib/$OARCH-linux-gnu/$LPATH/opera_sandbox
	ln -sf /usr/lib/$OARCH-linux-gnu/$LPATH/$LPATH usr/bin/opera
	LDIR=`find usr/ -type d -name localization`
	find $LDIR -name "*.pak" | egrep -v "fil.pak|$CHOICE|en-US" | xargs -i rm {}
	;;
esac

#makepkg -l y -c n $WRKDIR/${OP}-${RVERS}-$MARCH-$CHOICE-1.txz || { red "Failed to create slackware package."; exit 1; }
cd $WRKDIR
#txz2xzm ${OP}-${RVERS}-$MARCH-$CHOICE-1.txz || { red "Failed to create porteus module."; exit 1; }
dir2xzm $TMPDIR/build ${OP}-${RVERS}-$MARCH-$CHOICE-1.xzm || { red "Failed to create porteus module."; exit 1; }

echo
echo "Your file is at:" $txtgreen "$WRKDIR/$OP-$RVERS-$MARCH-$CHOICE-1.xzm" $rst
cyan "Please copy it to your modules folder to survive a reboot."
echo
check_gsettings
cleanup
