#!/bin/bash

# Automatic download, compile, and install of new Fl* code
#
# 02/14/21 - Made script more universal to support DEB systems; enhanced to have one
#            script be universal for all builds
# 03/14/19 - Updated the Alphas check section
# 01/25/17 - Added support for Alphas to edit a different SPEC
# 03/06/16 - Added w1hkj.com alpha releases
# 03/24/16 - Added automatic build mode
# 11/11/15 - Updated to use SF URLs
# 09/14/15 - minor cleanups for showing right RPM files, etc
# 02/03/14 - Added root compiling checking
# 02/03/13 - Added old/new version checking
# 12/20/12 - version sort now using -n to be more accurate for say flamp-1.0.01
#          - Adding duplicate download check
# 11/11/12 - Script made more universal
# 05/15/11

#program to fetch and compile
PROG="fldigi"


#Set this to a 1 if you want to download SPECIAL vs ALPHA vs PRODUCTION releases
USEALPHA=0

#Tools
CP="/bin/cp"
RPM="/bin/rpm"

# Is this source code from a remote URL or local filepath
# 0 = remote tarball
# 1 = local tarball only
MANUALRUN=0

#Automatically download and build if newer found?
AUTOMATIC=1

#Compile anywany even if installed version is same as remote version
FORCEBUILD=1

#Fldigi Configuration file paths
FLPREFFILE="/home/dranch/.$PROG/$PROG.prefs"
FLDEFFILE="/home/dranch/.$PROG/$PROG_def.xml"
FLLOGFILE="/home/dranch/.$PROG/logs/logbook.adif"

#RPM specific PATHS
RPMDLPATH="/usr/src/redhat/SOURCES/"
RPMSPECPATH="/usr/src/redhat/SPECS/"

#DEB specific PATHs
DEBDLPATH="/usr/src/packaging/$PROG"



#------------------------------------------------------------------------------
# Main program

#--------------------
#Figure out which URLs to use: main or alpha
if [ $USEALPHA -eq 1 ]; then
   #Fldigi Alpha releases from w1hkj.com directly
   CHKURL="http://www.w1hkj.com/alpha/$PROG/"
   DLURL="http://www.w1hkj.com/alpha/$PROG/"

   #Other specials
   #DLURL="http://www.w1hkj.com/alpha/test/"
   #DLURL="http://www.w1hkj.com/alpha/dranch/"

   #This is old#Uncomment out the below line for official Fldigi ALPHA releases (make sure the MAJOR releases section above is commented out)
   #CHKURL="https://sourceforge.net/projects/fldigi/rss?path=/alpha_tests"
   #DLURL="https://sourceforge.net/projects/$PROG/files/alpha_tests/"
  else
   #MAJOR releases (make sure the ALPHA section below is commented out)
   CHKURL="https://sourceforge.net/projects/fldigi/rss?path=/$PROG"
   DLURL="http://downloads.sourceforge.net/project/fldigi/$PROG/"
fi


#in program variables
#--------------------
#var to track if there is a new package to install
NEWPKG=0


#--------------------------
# functions
function CHKERR {
   if [ $? -ne 0 ]; then
      echo -e "\nERROR:  The last commmand failed.  Aborting.\n"
      exit 1
   fi
}

#--------------------------
# Main script body

if [ $UID -eq 0 ]; then
   echo -e "\nYou should NOT be root to run this command"
   echo -e "Exiting\n"
   exit 1
fi

#Remind the user they are building unstable ALPHA code
if [ $USEALPHA -eq 1 ]; then
   echo -e "\nUsing ALPHA files.  Starting in 3 seconds"
   sleep 3
fi

#override if specified on the command line
if [ -n "`echo $0 | grep manual`" ]; then
   echo -e "\nThis is a manual run"
   MANUALRUN=1
fi


#Which Linux OS type
if [ -f /etc/redhat-release ]; then
   echo -e "RPM-style OS found"
   OSTYPE="RPM"
   DLPATH=$RPMDLPATH
  elif [ -n "`grep ID_LIKE /etc/os-release | grep debian`" ]; then
   echo -e "DEB-style OS found"
   OSTYPE="DEB"
   DLPATH=$DEBDLPATH
  else
   echo -e "\nNon-recognized Linux packaging system; aborting\n"
   exit 1
fi


echo -e "\nDLURL is: $DLURL"
echo -en "\nDeterming current installed version of program: $PROG - "
if [ $OSTYPE == "RPM" ]; then
   INSTALLEDPKG="`rpm -qa | grep $PROG | awk -F - '{print $2}'`"
   echo -e "$INSTALLEDPKG"
  elif [ $OSTYPE == "DEB" ]; then
       INSTALLEDPKG="`dpkg -l | grep $PROG | awk '{print $3}' | head --lines=1 | awk -F- '{print $1}'`"
       if [ -z $INSTALLEDPKG ]; then
          INSTALLEDPKG="none"
          echo -e "$INSTALLEDPKG"
       fi
fi

if [ $MANUALRUN -eq 0 ]; then
   echo -en "Determing available version of program:         $PROG - "
   #determine newest version of Flrig
   #FLRIGNEWVERSION="`links --dump $DLURL | grep "tar.gz" | grep \* | \
   #grep -iv elp | sort -r | head -n1 | awk -F ] '{print $2}'`"
   if [ $USEALPHA -eq 1 ]; then
      FLPROGNEWVERSION="`wget -q -O - $CHKURL | grep $PROG- | grep tar.gz | awk -F\\" '{print $2}'`"
     else
      FLPROGNEWVERSION="`wget -q -O - $CHKURL | grep title | grep $PROG- | grep tar.gz | awk -F/ '{print $3}' | awk -F] '{print $1}' | head -n1`"
   fi

   if [ -z "$FLPROGNEWVERSION" ]; then
      echo -e "\nERROR: couldn't determine current newest version of $PROG"
      exit 1
     else
      #echo -e "$FLPROGNEWVERSION" | awk -F - '{print $2}' | awk -F . '{print $1"."$2"."$3}'
      if [ "`echo -e "$FLPROGNEWVERSION" | awk -F - '{print $2}' | awk -F . '{print $5}'`" = "tar" ]; then
         CLEARNEWVERSION="`echo -e "$FLPROGNEWVERSION" | awk -F - '{print $2}' | awk -F . '{print $1"."$2"."$3"."$4}'`"
         echo "$CLEARNEWVERSION"
        elif [ "`echo -e "$FLPROGNEWVERSION" | awk -F - '{print $2}' | awk -F . '{print $4}'`" = "tar" ]; then
         CLEARNEWVERSION="`echo -e "$FLPROGNEWVERSION" | awk -F - '{print $2}' | awk -F . '{print $1"."$2"."$3}'`"
         echo "$CLEARNEWVERSION"
      fi
   fi

   if [ $AUTOMATIC -eq 0 ]; then
      echo -e "Automatic build: Disabled"
      echo -en "\nProceed to download new code version [y|n]: "
      read USERINPUT
      if [ "$USERINPUT" == "n" ]; then
         echo -e "\nDownload aborted.  Exiting\n"
         exit 0
      fi
     else
      echo -e "\nAutomatic build: Enabled"
      if [ $INSTALLEDPKG == $CLEARNEWVERSION ]; then
         echo -e "   No new version availale.. skipping\n"
         if [ $FORCEBUILD -eq 1 ]; then
            echo -e "\nFORCEBUILD set: rebuilding package even though we're up to date"
           else
            exit 1
         fi
        else
         echo -e "   New version available.  Starting..\n"
      fi
   fi
fi

if [ ! -d $DLPATH ]; then
   echo -e "\nERROR: $DLPATH doesn't exist.  Please create it and try again.  Aborting\n"
   exit 1
fi

cd $DLPATH
if [ -f $FLPROGNEWVERSION ]; then
   echo -e "$FLPROGNEWVERSION already exists.. skipping the re-download"
  else
   if [ $MANUALRUN -eq 1 ]; then
      echo -e "\nERROR: source file $FLPROGNEWVERSION is not present"
      exit 1
   fi
   echo -e "\nGetting $DLURL/$FLPROGNEWVERSION and putting it in $DLPATH\n------------------------------------------------------------------\n"
   wget $DLURL/$FLPROGNEWVERSION
fi

echo -e "\n"

#if [ $OSTYPE == "RPM" ]; then
#   echo -e "BLAH: not implimented yet"
#  elif [ $OSTYPE == "DEB" ]; then
#        echo -e "BLAH: not implimented yet"
#fi

if [ $OSTYPE == "RPM" ]; then
   cd $RPMSPECPATH
   if [ $USEALPHA -eq 1 ]; then
      echo -e "Make a backup of the previous ALPHA SPEC file"
      $CP -vf $PROG-alpha.spec Old/$PROG-alpha-`grep Version $PROG.spec | awk '{print $2}'`.spec
     else
      echo -e "Make a backup of the previous RELEASE SPEC file"
      $CP -vf $PROG.spec Old/$PROG-`grep Version $PROG.spec | awk '{print $2}'`.spec
   fi

   echo -e "\nReady to manually update the spec file?\n[Press any key]\n"
   read ANYKEY

   if [ $USEALPHA -eq 1 ]; then
      vim $PROG-alpha.spec
     else
      vim $PROG.spec
   fi
  elif [ $OSTYPE == "DEB" ]; then
       #echo "DEBUG: FLPROGNEWVERSION is $FLPROGNEWVERSION"
       echo -e "Uncompress the archive"
       tar xzvf $FLPROGNEWVERSION

       cd $PROG-$CLEARNEWVERSION

       #TEMPORARY: work around for packaging on DEB systems
       echo -e "\nFetching DEB packaging details"
       if [ $PROG == "fldigi" ]; then
          wget http://deb.debian.org/debian/pool/main/f/$PROG/$PROG\_$CLEARNEWVERSION-1.debian.tar.xz
          tar xJvf $PROG\_$CLEARNEWVERSION-1.debian.tar.xz
         elif [ $PROG == "flrig" ]; then
              #version 1.3.54 isn't posted
              wget http://deb.debian.org/debian/pool/main/f/flrig/flrig_1.3.53-1.debian.tar.xz
              tar xJvf flrig_1.3.53-1.debian.tar.xz
       fi

       echo -e "\nTEMPORARY: optimize the build"
       patch -p0 < ../$PROG-*.patch
       CHKERR

       echo -e "\nReady to manually update the changelog file to reflect the new version?\n[Press any key]\n"
       read ANYKEY

       vim debian/changelog
fi


if [ $OSTYPE == "RPM" ]; then
   echo -e "\nCompiling $PROG RPM"
   if [ "`/bin/uname -m`" = "i686" ]; then
      echo -e "Found i686"
      if [ $USEALPHA -eq 1]; then
         rpmbuild -bb --target i686 $PROG-alpha.spec
         if [ $? -ne 0 ]; then
            echo -e "\n------------------------------------------"
            echo -e "Error: $PROD did not successfully compile!"
            echo -e "\nExiting!"
            echo -e "------------------------------------------\n"
            exit 1
         fi
         echo -e "\nAssuming all went well, please manually upgrade the installed RPM with"
         echo -e "\n    rpm -Uvh /usr/src/redhat/RPMS/i686/$FLPROGNEWVERSION"
        else
         rpmbuild -bb --target i686 $PROG.spec
         if [ $? -ne 0 ]; then
            echo -e "\n------------------------------------------"
            echo -e "Error: $PROD did not successfully compile!"
            echo -e "\nExiting!"
            echo -e "------------------------------------------\n"
            exit 1
         fi
         echo -e "\nAssuming all went well, please manually upgrade the installed RPM with"
         echo -e "\n    rpm -Uvh /usr/src/redhat/RPMS/i686/$FLPROGNEWVERSION"
      fi
     elif [ "`/bin/uname -m`" = "x86_64" ]; then
      echo -e "Found x86_64"
      if [ $USEALPHA -eq 1 ]; then
         rpmbuild -bb --target=x86_64 $PROG-alpha.spec
         if [ $? -ne 0 ]; then
            echo -e "\n------------------------------------------"
            echo -e "Error: $PROD did not successfully compile!"
            echo -e "\nExiting!"
            echo -e "------------------------------------------\n"
            exit 1
          else
            #New package made, enable flag
            NEWPKG=1
            echo -e "\nPlease manually upgrade the installed RPM with"
            echo -e "\n    sudo rpm -Uvh /usr/src/redhat/RPMS/x86_64/$FLPROGNEWVERSION" | sed s/.tar.gz/-1.el6.x86_64.rpm/
         
            #If run from the update-fl-suite.sh script, provide one file to run and do cleanups
            DATE="`date +%m%d%y`"
            if [ ! -f /tmp/fl-update-$DATE.sh ]; then
               echo -e "sudo rpm -Uvh /usr/src/redhat/RPMS/x86_64/$FLPROGNEWVERSION" | sed s/.tar.gz/-1.el6.x86_64.rpm/ > /tmp/fl-update-$DATE.sh
              else
               #Append
               echo -e "sudo rpm -Uvh /usr/src/redhat/RPMS/x86_64/$FLPROGNEWVERSION" | sed s/.tar.gz/-1.el6.x86_64.rpm/ >> /tmp/fl-update-$DATE.sh
            fi
            chmod 700 /tmp/fl-update-$DATE.sh
         fi
        else
         rpmbuild -bb --target=x86_64 $PROG.spec
         if [ $? -ne 0 ]; then
            echo -e "\n------------------------------------------"
            echo -e "Error: $PROD did not successfully compile!"
            echo -e "\nExiting!"
            echo -e "------------------------------------------\n"
            exit 1
          else
            #New package made, enable flag
            NEWPKG=1
            echo -e "\nPlease manually upgrade the installed RPM with"
            echo -e "\n    sudo rpm -Uvh /usr/src/redhat/RPMS/x86_64/$FLPROGNEWVERSION" | sed s/.tar.gz/-1.el6.x86_64.rpm/
            #If run from the update-fl-suite.sh script, provide one file to run and do cleanups
            DATE="`date +%m%d%y`"
            if [ ! -f /tmp/fl-update-$DATE.sh ]; then
               echo -e "sudo rpm -Uvh /usr/src/redhat/RPMS/x86_64/$FLPROGNEWVERSION" | sed s/.tar.gz/-1.el6.x86_64.rpm/ > /tmp/fl-update-$DATE.sh
              else
               #Append
               echo -e "sudo rpm -Uvh /usr/src/redhat/RPMS/x86_64/$FLPROGNEWVERSION" | sed s/.tar.gz/-1.el6.x86_64.rpm/ >> /tmp/fl-update-$DATE.sh
            fi
            chmod 700 /tmp/fl-update-$DATE.sh
         fi
      fi
   fi
  elif [ $OSTYPE == "DEB" ]; then
       echo -e "\nCompiling $PROG DEB"
       debuild --no-tgz-check -i -b -us -uc
       CHKERR
fi

echo -e "\nMaking a backup of key files just in case"
DATE="`date +%m%d%y`"
echo -en "$FLPREFFILE "
cp $FLPREFFILE $FLPREFFILE-$DATE.bak
echo -e "$FLDEFFILE "
cp $FLDEFFILE $FLDEFFILE-$DATE.bak
if [ $PROG == "fldigi" ]; then
   echo -en "$FLLOGFILE "
   cp $FLLOGFILE $FLLOGFILE-$DATE.bak
fi

#ls -la *-$DATE.bak

echo -e "\n\nDone!\n\n"
if [ $NEWPKG -eq 1 ]; then
   #indicate we have a new package
   exit 100
  else
   exit 0
fi
