#!/bin/sh
#package manager for Puppy Linux.
#(c) copyright 2005,2006,2007 Barry Kauler www.puppyos.com
#v2.13 substantially modified.
#v2.14 LGPL
#2007 Lesser GPL licence v2 (http://www.fsf.org/licensing/licenses/lgpl.html)

#optional passed param is a pkg name preceded by a + to install pkg, - to uninstall pkg.
# pkg name example: xbubble-0.2.4
# for install, petget script will offer download URLs or local.
#New for v2.13, integration with Rox-Filer. If commandline is a .pet with
# absolute path, ex: petget /root/xbubble-0.2.4.pet
# petget script will simply install it.
#also added a url, ex: petget http://somewhere.on.internet/xbubble-0.2.4.pet

#13Sept2007 BK: v2.21 handle true flushing to flash drive.Oct 2007: v3.01 updates.

#v2.17.1 trying to fix a bug...
LANG=C
export LANG

PUPPYVERSION="`cat /etc/puppyversion`"
#v2.17.1 variables created at bootup by /initrd/usr/sbin/init...
. /etc/rc.d/PUPSTATE  #this has PUPMODE and SAVE_LAYER.

#v2.21 boot from flash, bypass tmpfs, install direct to pup_save file...
DIRECTSAVEPATH=""
if [ $PUPMODE -eq 3 -o $PUPMODE -eq 7 -o $PUPMODE -eq 13 ];then
 if [ "`lsmod | grep '^unionfs' `" != "" ];then
  #if snapmergepuppy is running, wait until it has finished...
  while [ "`pidof snapmergepuppy`" != "" ];do
   sleep 1
  done
  DIRECTSAVEPATH="/initrd${SAVE_LAYER}"
 fi
fi

#  <frame>
#   <text><label>Or, you can install any downloaded PET package (official or unofficial) just by clicking on it in ROX-Filer file manager.</label></text>
#  </frame>

#<text><label>Click INFORMATION button to find out more about this package before installation</label></text>
#  <text><label>\"  \"</label></text>
#   <button><input file>/usr/local/lib/X11/mini-icons/info16.xpm</input><label>INFORMATION</label><action>EXIT:12</action></button>
#   <text><label>\" \"</label></text>
  

#v2.0.0 main dlg...
DLG1="
 <wtitle>PETgetパッケージマネージャ</wtitle>
 <vbox>
  <text><label>PETパッケージマネージャにようこそ！</label></text>
  <text><label>PETパッケージは2種類あります。「公式」と「非公式」です。 公式PETパッケージは「放し飼い（＝自由に選べる）パッケージソフト」から来ています。あなたが今使っているパピーを作るために使われたパッケージ群です。非公式パッケージはその名の通り、誰かによって作成されたものです。あなたが何が欲しいか、あるいは最大限の互換性のためには、最初に公式PETパッケージに目を通す事をお勧めします。</label></text>
  <hbox>
<text><label>公式PETパッケージの選択とインストール、またインストールされている（公式・非公式）PETパッケージのアンインストールをするには、ボタンをクリックして下さい:</label></text>
   <vbox>
    <button>
     <input file>/usr/local/lib/X11/pixmaps/packaging48.xpm</input>
     <action>EXIT:10</action>
    </button>
   </vbox>
  </hbox>
  <text><label>\" \"</label></text>
  
  <hbox>
   <text><label>あるいは、ダウンロードした公式、非公式PETパッケージがあれば、このボタンをクリックすればインストールできます:</label></text>
   <vbox>
    <button>
     <input file>/usr/local/lib/X11/mini-icons/pupget.xpm</input>
     <action>EXIT:13</action>
    </button>
   </vbox>
  </hbox>

  <hbox>
   <text><label>PETパッケージのインストール時に依存性がチェックされます。しかしインストールされたどのパッケージも、このボタンをクリックすれば再テストできます。これはすべての必要な共有ライブラリがあるかテストします:</label></text>
   <vbox>
    <button>
     <input file>/usr/local/lib/X11/mini-icons/package.xpm</input>
     <action>EXIT:11</action>
    </button>
   </vbox>
  </hbox>

  <frame 詳細情報>
   <text><label>「ROXファイラ」ファイルマネージャを使えば、ダウンロードしたどんな（公式・非公式な）PETパッケージでもクリックするだけでインストールできます。ダウンロードしてクリックするだけ、とても簡単です！</label></text>
   <hbox>
    <text><label>PETパッケージについてもっと勉強したいですか？ホームページでの情報はボタンをクリックして下さい:</label></text>
    <vbox>
     <button>
      <input file>/usr/local/lib/X11/mini-icons/info16.xpm</input>
      <action>/usr/local/bin/defaultbrowser http://www.puppylinux.com/development/package-management.htm &</action>
     </button>
    </vbox>
   </hbox>
  </frame>
  <button cancel></button>
 </vbox>
"



#v2.13 this code very untidy, will do a house clean sometime...
COMMANDPKG=""
DISABLEDX=""
ROXCMD=""
if [ "$1" ];then
 COMMANDPKG="$1"
 #want pet script to be noninteractive.
 #passed param is a pkg name preceded by a + to install pkg, - to uninstall pkg.
 if [ "`echo -n "$COMMANDPKG" | cut -b 1`" = '-' ];then
  RETVAL="`xmessage -center -timeout 1 "testing" 2>&1`"
  if [ ! "`echo "$RETVAL" | grep "Error:"`" = "" ];then
   #this situation only when uninstalling a pkg, so haven't bypassed all xmessages.
   DISABLEDX="yes"
  fi
 fi
 #expanding pet to work with rox...
 #if the commandline has a full path/filename then no need to ask about where
 #to download it from....
 CMD1STCHAR="`echo -n "$COMMANDPKG" | cut -b 1`"
 if [ "$CMD1STCHAR" = "/" ];then
  ROXCMD="$COMMANDPKG"
  #now extract just the pkg name, no path, no extension...
  COMMANDPKG="+`basename "$ROXCMD" .pet`"
 fi
 #also accept a url...
 if [ ! "`echo -n "$COMMANDPKG" | grep --extended-regexp '^ftp:|^http:'`" = "" ];then
  ROXCMD="$COMMANDPKG"
  #now extract just the pkg name, no path, no extension...
  COMMANDPKG="+`basename "$ROXCMD" .pet`"
 fi
fi

THISVER="`cat /etc/puppyversion`"
DIGIT1="`echo "$THISVER" | cut -b 1`"
DIGIT2="`echo "$THISVER" | cut -b 2`"
DIGIT3="`echo "$THISVER" | cut -b 3`" 
RIGHTVER="${DIGIT1}.${DIGIT2}.${DIGIT3}"

#WKGDIR="`pwd`"
WKGDIR="/root/.packages"
cd /root/.packages

##so that can restore if abort at later stage...
#backupfunc() {
# cp -af $WKGDIR/packages.txt /tmp/packages.txt.orig
# if [ -f $WKGDIR/alienpackages.txt ];then
#  cp -af $WKGDIR/alienpackages.txt /tmp/alienpackages.txt.orig
# else
#  rm -f /tmp/alienpackages.txt.orig 2>/dev/null
# fi
# if [ -f $WKGDIR/livepackages.txt ];then
#  cp -af $WKGDIR/livepackages.txt /tmp/livepackages.txt.orig
# else
#  rm -f /tmp/livepackages.txt.orig 2>/dev/null
# fi
#}
#backupfunc #call it.

#restorefunc() {
# cp -af /tmp/packages.txt.orig $WKGDIR/packages.txt
# if [ -f /tmp/alienpackages.txt.orig ];then
#  cp -af /tmp/alienpackages.txt.orig $WKGDIR/alienpackages.txt
# else
#  rm -f $WKGDIR/alienpackages.txt 2>/dev/null
# fi
# if [ -f /tmp/livepackages.txt.orig ];then
#  cp -af /tmp/livepackages.txt.orig $WKGDIR/livepackages.txt
# else
#  rm -f $WKGDIR/livepackages.txt 2>/dev/null
# fi
#}

dependcheckfunc() {
 FLAGDEPPKG="no"
 [ "$WKGDIR" = "" ] && WKGDIR='.' #i expect this to be set, precaution.
 echo -n "" > /tmp/missinglibs.txt
 echo -n "" > /tmp/missinglibs0.txt
  #v1.0.4 
  #for openoffice, really need to add /usr/OpenOffice.org1.1.4/program to LD_LIBRARY_PATH,
  #but cannot be bothered for now... nah, do something now...
  if [ ! "`echo -n "$APKGNAME" | grep "openoffice"`" = "" ];then
   #return #bypass dependency check.
   if [ "`echo "$LD_LIBRARY_PATH" | grep "OpenOffice"`" = "" ];then
    LD_LIBRARY_PATH="/usr/OpenOffice.org1.1.4/program:$LD_LIBRARY_PATH"
    export LD_LIBRARY_PATH
    #...need to generalise this code for different versions of openoffice.
   fi
  fi
 #APATTERN="s/.\/$APKGNAME//g"
 #cd $WKGDIR
 #FNDFILES="`find ./$APKGNAME -type f | sed -e "$APATTERN" | tr "\n" " "`"
 FNDFILES="`cat $WKGDIR/$APKGNAME.files`"
 for ONEFILE in $FNDFILES
 do
  ISANEXEC="`file --brief $ONEFILE | grep --extended-regexp "LSB executable|shared object"`"
  if [ ! "$ISANEXEC" = "" ];then
   LDDRESULT="`ldd $ONEFILE`"
   MISSINGLIBS="`echo "$LDDRESULT" | grep "not found" | cut -f 2 | cut -f 1 -d " " | tr "\n" " "`"
   if [ ! "$MISSINGLIBS" = "" ];then
    echo "File $ONEFILE has these missing library files:" >> /tmp/missinglibs.txt
    echo " $MISSINGLIBS" >> /tmp/missinglibs.txt
   fi
  fi
 done
 sync
 #find any dependent packages...
 #second field in comments-field has a comma-delimited list of dependencies...
 cp -f $WKGDIR/packages.txt /tmp/tempzzz
 [ -f $WKGDIR/livepackages.txt ] && cat $WKGDIR/livepackages.txt >> /tmp/tempzzz
 [ -f $WKGDIR/alienpackages.txt ] && cat $WKGDIR/alienpackages.txt >> /tmp/tempzzz
 BPATTERN="^\"${APKGNAME}\" "
 #creates list, each line in format "pkgname ...
 DEPENDPKGS="`cat /tmp/tempzzz | grep "$BPATTERN" | head -n 1 | cut -f 6 -d '"' | cut -f 2 -d " " | tr "," "\n" | grep "^\+" |  sed -e 's/^\+/"/g'`"
 if [ ! "$DEPENDPKGS" = "" ];then
#  echo "Package $APKGNAME has these missing packages that it is dependent on:" >> /tmp/missinglibs.txt
  for ADEPENDPKG in $DEPENDPKGS
  do
   if [ "`echo "$ADEPENDPKG" | grep '\-'`" = "" ];then
    BPATTERN="^${ADEPENDPKG}\\-"
   else
    BPATTERN="^${ADEPENDPKG}\" "
   fi
   if [  "`cat /tmp/tempzzz | grep '" on "' | grep "$BPATTERN"`" = "" ];then
    FLAGDEPPKG="yes"
    echo "This dependent package is missing: $ADEPENDPKG\" " >> /tmp/missinglibs.txt
    #should find the exact missing pkg name, so can get it...
    #but what if it is already in the PKGS2ADD list?
    if [ "`echo "$PKGS2ADD" | grep "$BPATTERN"`" = "" ];then
     MPKGLINE="`cat $WKGDIR/livepackages.txt | grep '" off "' | grep "$BPATTERN" | head -n 1`"
     if [ ! "$MPKGLINE" = "" ];then
      echo "$MPKGLINE" >> /tmp/missingpkgs.txt #will become next PKGS2ADD list.
      # #this missing pkg will get queued for installation, so better turn it on now...
      # MPKGNAME="`echo -n "$MPKGLINE" | cut -f 2 -d '"'`" #'geany fix.
      # MPATTERN="^\"${MPKGNAME}\" "
      # cat $WKGDIR/livepackages.txt | grep -v "$MPATTERN" > /tmp/tempvvvv
      # sync
      # echo "$MPKGLINE" | sed -e 's/\" off \"/\" on \"/g' >> /tmp/tempvvvv
      # sort /tmp/tempvvvv > $WKGDIR/livepackages.txt
      # rm -f /tmp/tempvvvv
     fi
    else
     echo "...however you do have it queued for installation next, so ok." >> /tmp/missinglibs.txt
    fi
   fi
  done
 fi
 TESTONLY=""
} #end dependcheckfunc


installpkgfunc () {
    if [ -f ./$APKGNAME/puninstall.sh ];then
     mv ./$APKGNAME/puninstall.sh ./$APKGNAME.remove
    fi
    if [ -d ./$APKGNAME/root0 ];then #for an old legacy pre-v2.14 pkg
     mv ./$APKGNAME/root0 ./$APKGNAME/root
    fi
    if [ -f ./$APKGNAME/keyword ];then
     #mv ./$APKGNAME/keyword ./$APKGNAME.keyword
     rm -f ./$APKGNAME/keyword
    fi
    #if [ -f ./$APKGNAME.keyword ];then
    # #code here to add menu entries etc...
    # AKEYWORD="`cat ./$APKGNAME.keyword | cut -f 1 -d " "`"
    # #v1.0.5
    # #v2.14 with xdg menus this is now mostly redundant...
    # /usr/sbin/fixmenus /root $AKEYWORD
    #fi
    #v1.0.2 problem, these images must be in .files file so can be uninstalled...
    for ONEIMAGEFILE in `ls -1 ./$APKGNAME/*[0-9].xpm 2>/dev/null`
    do
     BASEONEIMAGE="`basename $ONEIMAGEFILE`"
     echo "/usr/local/lib/X11/pixmaps/$BASEONEIMAGE" >> ./$APKGNAME.files
    done
    for ONEIMAGEFILE in `ls -1 ./$APKGNAME/*[0-9].png 2>/dev/null`
    do
     BASEONEIMAGE="`basename $ONEIMAGEFILE`"
     echo "/usr/local/lib/X11/pixmaps/$BASEONEIMAGE" >> ./$APKGNAME.files
    done
    for ONEIMAGEFILE in `ls -1 ./$APKGNAME/*[^0-9].xpm 2>/dev/null`
    do
     BASEONEIMAGE="`basename $ONEIMAGEFILE`"
     echo "/usr/local/lib/X11/mini-icons/$BASEONEIMAGE" >> ./$APKGNAME.files
    done
    for ONEIMAGEFILE in `ls -1 ./$APKGNAME/*[^0-9].png 2>/dev/null` #v2.16
    do
     BASEONEIMAGE="`basename $ONEIMAGEFILE`"
     echo "/usr/local/lib/X11/mini-icons/$BASEONEIMAGE" >> ./$APKGNAME.files
    done
    sync
    #...images.files is appended to the .files file further down.
    #window and menu icons can also be in the top-level directory of the package...
    mkdir -p ${DIRECTSAVEPATH}/usr/local/lib/X11/pixmaps #v2.21
    mkdir -p ${DIRECTSAVEPATH}/usr/local/lib/X11/mini-icons #v2.21
    mv ./$APKGNAME/*24.xpm ${DIRECTSAVEPATH}/usr/local/lib/X11/pixmaps/ 2>/dev/null
    mv ./$APKGNAME/*32.xpm ${DIRECTSAVEPATH}/usr/local/lib/X11/pixmaps/ 2>/dev/null
    mv ./$APKGNAME/*32.png ${DIRECTSAVEPATH}/usr/local/lib/X11/pixmaps/ 2>/dev/null
    mv ./$APKGNAME/*48.xpm ${DIRECTSAVEPATH}/usr/local/lib/X11/pixmaps/ 2>/dev/null
    mv ./$APKGNAME/*48.png ${DIRECTSAVEPATH}/usr/local/lib/X11/pixmaps/ 2>/dev/null
    mv ./$APKGNAME/*.xpm ${DIRECTSAVEPATH}/usr/local/lib/X11/mini-icons/ 2>/dev/null
    mv ./$APKGNAME/*.png ${DIRECTSAVEPATH}/usr/local/lib/X11/mini-icons/ 2>/dev/null #v2.16
    #now copy files to destination...
     #v1.0.5
     #problem if jwm or fvwm95 not installed by Unleashed. Unleashed createpuppy script
     #installs .jwmrc and .fvwm95rc anyway and processes them, so do not overwrite them
     #if install jwm or fvwm95 pets now...
     cp -f /root/.fvwm95rc /tmp/fvwm95rcBACKUP
     cp -f /root/.jwmrc /tmp/jwmrcBACKUP
     cp -f /root/.icewm/menu /tmp/icemenuBACKUP
    #cp -a ./$APKGNAME/* / #stupid thing objects '/etc is not a directory'. so...
    #cp -af ./$APKGNAME/* / 2> /dev/null #nup, not there yet...
    #problem if src is a file, dest is a link... dillo for example, /usr/local/bin/dillo
    #is a link to gtkmoz, so cp writes dillo file over gtkmoz. Removing package leaves
    #incorrect gtkmoz behind. so trying different copy options...
    cp -a --remove-destination ./$APKGNAME/* ${DIRECTSAVEPATH}/ 2> /dev/null
    cp -a --remove-destination ./$APKGNAME/etc/* ${DIRECTSAVEPATH}/etc/
    sync
    
    #v2.21 flush unionfs cache...
    if [ "$DIRECTSAVEPATH" != "" ];then
     #but first, clean out any bad whiteout files...
     find $SNAP -mount -type f -name .wh.\* |
     while read ONEWHITEOUT
     do
      ONEWHITEOUTFILE="`basename "$ONEWHITEOUT"`"
      ONEWHITEOUTPATH="`dirname "$ONEWHITEOUT"`"
      if [ "$ONEWHITEOUTFILE" = ".wh.__dir_opaque" ];then
       [ "`grep "$ONEWHITEOUTPATH" /root/.packages/${APKGNAME}.files`" != "" ] && rm -f "$ONEWHITEOUT"
       continue
      fi
      ONEPATTERN="`echo -n "$ONEWHITEOUT" | sed -e 's%/\.wh\.%/%'`"'$'
      [ "`grep "$ONEPATTERN" /root/.packages/${APKGNAME}.files`" != "" ] && rm -f "$ONEWHITEOUT"
     done
     #now re-evaluate all the layers...
     mount -t unionfs -o remount,incgen unionfs /
     #sleep 1
     sync
    fi
    
     #now restore w.m. config files...
     cp -f /tmp/fvwm95rcBACKUP /root/.fvwm95rc
     cp -f /tmp/jwmrcBACKUP /root/.jwmrc
     cp -f /tmp/icemenuBACKUP /root/.icewm/menu
    if [ -f ./$APKGNAME/pinstall.sh ];then
     cd /
     /pinstall.sh #execute post-install script.
     rm -f /pinstall.sh
     cd $WKGDIR #/root/.packages
    fi
    if [ -d ./$APKGNAME ];then
    
     if [ -d /install ];then #slackware pkg installs this.
      #for now, do nothing with this, just delete it...
      #no, let's run the install script...
      if [ -f /install/doinst.sh ];then
       chmod +x /install/doinst.sh
       cd /
       sh /install/doinst.sh
       cd $WKGDIR
      fi
      rm -rf /install
     fi

     #there should be a '$APKGNAME.pet.specs' file created by pup2pet script...
     #this has variables PETMENUDESCR, PETOFFICIALDEPS, PETREGISTER...
     [ -f /${APKGNAME}.pet.specs ] && rm -f /${APKGNAME}.pet.specs #this got installed too.
     PETREGISTER="";PETMENUDESCR="";PETOFFICIALDEPS=""
     if [ -f $WKGDIR/$APKGNAME/${APKGNAME}.pet.specs ];then
. $WKGDIR/$APKGNAME/${APKGNAME}.pet.specs
     else
      PETMENUDESCR=''
      PETOFFICIALDEPS=''
      PETREGISTER='yes'
     fi
     
     yaf-splash -font "8x16" -outline 0 -margin 4 -bg orange -text "PETget package manager
Updating menu, please wait..." & #9x15B also looks okay.
     MENUPID=$!
     #master help index has to be updated...
     #to speed things up, find the help files in the new pkg only...
     /usr/sbin/indexgen.sh ${WKGDIR}/${APKGNAME}
     #Reconstruct configuration files for JWM, Fvwm95, IceWM...
     /usr/sbin/fixmenus
     kill $MENUPID
     
     #this usually only applies to an alien pkg...
     if [ "$PETREGISTER" = "no" ];then
      gxmessage "PET パッケージ ${APKGNAME}.pet はインストールされました。
PETget に登録されていないのでアンインストールできません。"
      exit
     fi

     ADESKTOPFILE="`cat $WKGDIR/${APKGNAME}.files | grep '\.desktop$' | head -n 1`"
     #display a message that pkg installed, with useful info...
     AMSG="NOTE 1: This application does NOT have a menu entry."
     if [ ! "$ADESKTOPFILE" = "" ];then
      ACATEGORY="`cat $ADESKTOPFILE | grep '^Categories='  | cut -f 2 -d '=' | sed -e 's/.*;//g'`"
      APATTERN="[ ,]${ACATEGORY}$"
      TOPMENU="`cat /etc/xdg/menus/hierarchy | grep "${APATTERN}" | cut -f 1 -d ' '`"
      if [ "$TOPMENU" = "" ];then
       APATTERN="[ ,]${ACATEGORY},"
       TOPMENU="`cat /etc/xdg/menus/hierarchy | grep "${APATTERN}" | cut -f 1 -d ' '`"
      fi
      AMENUDESCR="`cat $ADESKTOPFILE | grep '^Name=' | cut -f 2 -d '='`"
      AMSG="エントリーは次のテキスト付きで '${TOPMENU}' メニューに作成されました。
'${AMENUDESCR}'
しかし新しいメニューを見るにはウィンドウマネージャのリスタートが必要です
（「シャットダウン」か「ウィンドウ」メニューを見て下さい）

注意１: /root/.packages/${APKGNAME}.ファイルは
             インストール済みファイルリストがあります"
     fi

     #dependency check code...
     yaf-splash -font "8x16" -outline 0 -margin 4 -bg orange -text "PETget package manager
Checking dependencies, please wait..." & #9x15B also looks okay.
     DEPSPID=$!
     dependcheckfunc #function to check dependencies.
     kill $DEPSPID
     rm -rf ./$APKGNAME
     if [ -s /tmp/missinglibs.txt ];then
      if [ ! "$DISABLEDX" = "yes" ];then
       if [ "$FLAGDEPPKG" = "yes" ];then
        WARNLIB="IMPORTANT: The PETget package manager has placed the missing packages in a queue and you will be asked later if you want to install them."
       else
        WARNLIB="The PETget package manager does not know what package has these libraries."
       fi
#       gxmessage -name "pet" -bg "#80ff80" -center -title "PETget" "SUCCESS: $APKGNAME is installed!
#
#${AMSG}
#NOTE 2: If installed any library, X server, browser, you must reboot Puppy.
#
#HOWEVER, these dependencies required by this package are missing:
#`cat /tmp/missinglibs.txt`
#
#$WARNLIB"
       xMISSINGLIBS="`cat /tmp/missinglibs.txt | tr '"' "'"`"
       DLG_REG2="
 <wtitle>PETget package manager</wtitle>
 <vbox>
  <pixmap><input file>/usr/local/lib/X11/pixmaps/ok.xpm</input></pixmap>
  <text><label>\"SUCCESS: ${APKGNAME} is installed!

${AMSG}
NOTE 2: If installed any library, X server, browser,
             you must reboot Puppy.\"</label></text>
  <pixmap><input file>/usr/local/lib/X11/pixmaps/error.xpm</input></pixmap>
  <text><label>\"HOWEVER, these dependencies are missing:
${xMISSINGLIBS}

${WARNLIB}\"</label></text>
  <text><label>\"  \"</label></text>
  <hbox>
  <button><input file>/usr/local/lib/X11/mini-icons/mini-tick.xpm</input><label>OKAY</label><action>EXIT:10</action></button>
  </hbox>
 </vbox>"
       echo "$DLG_REG2" | gtkdialog2 --stdin
      fi
     else
      if [ ! "$DISABLEDX" = "yes" ];then
#       gxmessage -name "pet" -bg "#80ff80" -center -title "PETget" "SUCCESS: $APKGNAME is installed!
#
#${AMSG}
#NOTE 2: If installed any library, X server, browser, you must reboot Puppy."
       DLG_REG3="
 <wtitle>PETget パッケージマネージャ</wtitle>
 <vbox>
  <pixmap><input file>/usr/local/lib/X11/pixmaps/ok.xpm</input></pixmap>
  <text><label>\"成功: ${APKGNAME} はインストールされました！\"</label></text>
  <text><label>\"
${AMSG}
注意２: ライブラリ、 X サーバ、ブラウザを１つでもインストールしたら、
             パピーをリブートしなければなりません。\"</label></text>
  <text><label>\"  \"</label></text>
  <hbox>
   <button><input file>/usr/local/lib/X11/mini-icons/mini-tick.xpm</input><label>OKAY</label><action>EXIT:10</action></button>
  </hbox>
 </vbox>"
       echo "$DLG_REG3" | gtkdialog2 --stdin

      fi
     fi
    
    else
     if [ ! "$DISABLEDX" = "yes" ];then
      gxmessage -name "pet" -bg "#ff8080" -center -title "PETget" "エラー: どこかおかしいです。 $APKGNAME はインストールされませんでした"
     fi
     RETSTATUS=1
    fi
    rm -f ./$APKGNAME.tar.gz
} #end installpkgfunc()


#v2.14 install a .pup package (embedded in a pet pkg)...
installpupfunc() {
 #location of .pup: ./$APKGNAME/${APKGNAME}.pup
 #current dir is /root/.packages, which WKGDIR is set to, but use variable.
 #some code based on 'dotpuprox.sh' written by GuestToo
 
 #save window manager config files, as will ignore what dotpup does to them...
 cp -f /root/.icewm/menu /tmp/WMBACKUP-menu
 cp -f /root/.jwmrc /tmp/WMBACKUP-jwmrc
 cp -f /root/.fvwm95rc /tmp/WMBACKUP-fvwm95rc
 #ditto these...
 cp -f $WKGDIR/alienpackages.txt /tmp/BACKUP-alienpackages.txt
 
 if ! unzip -t "$WKGDIR/$APKGNAME/${APKGNAME}.pup"
 then
  gxmessage -bg red -center -title "PETget エラー" "パッケージ ${APKGNAME}.pet の実体は「変換された.pup」パッケージです。
しかし元の ${APKGNAME}.pup ファイルには
ファイル完全性エラーがあります。
PETget はインストールを中止します..."
  return 1
 fi
 cd "$WKGDIR/$APKGNAME"
 if ! unzip -o "./${APKGNAME}.pup"
 then
  gxmessage -bg red -center -title "PETget エラー" "パッケージ ${APKGNAME}.pet の実体は変換された.pup」パッケージです。
しかし元の ${APKGNAME}.pup ファイルには
ファイル完全性エラーがあります。
PETget はインストールを中止します..."
  return 1
 fi
 rm -f ./${APKGNAME}.pup
 chmod a+x dotpup.sh
 #give full path just in case script wants it...
 installwatch -o /tmp/pupinstall.list $WKGDIR/$APKGNAME/dotpup.sh
 cd $WKGDIR
 
 #there should be a '$APKGNAME.pet.specs' file created by pup2pet script...
 if [ -f $WKGDIR/$APKGNAME/${APKGNAME}.pet.specs ];then #precaution.
. $WKGDIR/$APKGNAME/${APKGNAME}.pet.specs
 else
  PETMENUDESCR=''
  PETOFFICIALDEPS=''
  PETREGISTER='yes'
 fi

 yaf-splash -font "8x16" -outline 0 -margin 4 -bg orange -text "PETget package manager
Updating menu, please wait..." & #9x15B also looks okay.
 MENUPID=$!
 #master help index has to be updated...
 /usr/sbin/indexgen.sh ${WKGDIR}/${APKGNAME}
 #Reconstruct configuration files for JWM, Fvwm95, IceWM...
 /usr/sbin/fixmenus
 kill $MENUPID
     
 #create list of installed files...
 #last sed fixes a bug in .pup install script...
 cat /tmp/pupinstall.list | grep '#success$' | tr -s '\t' | tr '&' ' ' | tr '\t' '&' | grep '^4&open&' | grep --extended-regexp -v '&/dev/tty&|&/dev/null&|&/root/.packages/|&/tmp/|&/root/.icewm/|&/proc/|&/sys/' | cut -f 3 -d '&' | sed -e 's/^\/\//\//g' > /tmp/${APKGNAME}.files
 sync
 if [ ! -s /tmp/${APKGNAME}.files ];then
  #nothing got installed.
  #sometimes the dotpup installer has an option to abort the install.
  return 1
 fi

 #difficult task, separate package name from version part... 
 #not perfect, some start with non-numeric version info...
 ANAMEONLY="`echo -n "$APKGNAME" | sed -e 's/\-[0-9].*$//g'`"
 #...if that fails, do it the old way...
 [ "$ANAMEONLY" = "$APKGNAME" ] && ANAMEONLY="`echo "$APKGNAME" | cut -f 1 -d "-"`"

 #a dotpup or pet package could just be a bugfix or patch and do not want to
 #register it....
 if [ "$PETREGISTER" = "no" ];then #this is in the .specs file.
  #get rid of whatever dotpup registered with petget
  rm -f $WKGDIR/${APKGNAME}.files 2>/dev/null
  rm -f $WKGDIR/${APKGNAME}.keyword 2>/dev/null
  rm -f $WKGDIR/${APKGNAME}.remove 2>/dev/null
  #restore config files maybe modified by dotpup installer...
  cp -f /tmp/WMBACKUP-menu /root/.icewm/menu
  cp -f /tmp/WMBACKUP-jwmrc /root/.jwmrc
  cp -f /tmp/WMBACKUP-fvwm95rc /root/.fvwm95rc
  cp -f /tmp/BACKUP-alienpackages.txt $WKGDIR/alienpackages.txt
  return 0
 fi
 
 #get rid of whatever dotpup registered with petget (except .remove file)...
 #also wipe any earlier version...
 mv -f $WKGDIR/${APKGNAME}.remove /tmp/${APKGNAME}.remove
 rm -f $WKGDIR/${ANAMEONLY}*.files 2>/dev/null
 rm -f $WKGDIR/${ANAMEONLY}*.keyword 2>/dev/null
 rm -f $WKGDIR/${ANAMEONLY}*.remove 2>/dev/null
 mv -f /tmp/${APKGNAME}.remove $WKGDIR/${APKGNAME}.remove

 #the pup2pet script has the option of creating a .desktop file that will
 #override one already in the .pup package...
 if [ -f $WKGDIR/$APKGNAME/${ANAMEONLY}.desktop ];then
  #[ -f /usr/share/applications/${APKGNAME}.desktop ] && rm -f /usr/share/applications/${APKGNAME}.desktop
  #[ -f /usr/local/share/applications/${APKGNAME}.desktop ] && rm -f /usr/local/share/applications/${APKGNAME}.desktop
  rm -f `cat /tmp/${APKGNAME}.files | grep '\.desktop$' | head -n 1`
  cp -af $WKGDIR/$APKGNAME/${ANAMEONLY}.desktop /usr/share/applications/
  cat /tmp/${APKGNAME}.files | grep -v '\.desktop$' > /tmp/tempccc
  sync
  echo "/usr/share/applications/${ANAMEONLY}.desktop" >> /tmp/tempccc
  mv -f /tmp/tempccc /tmp/${APKGNAME}.files
 fi
 
 #restore config files maybe modified by dotpup installer...
 cp -f /tmp/WMBACKUP-menu /root/.icewm/menu
 cp -f /tmp/WMBACKUP-jwmrc /root/.jwmrc
 cp -f /tmp/WMBACKUP-fvwm95rc /root/.fvwm95rc
 cp -f /tmp/BACKUP-alienpackages.txt $WKGDIR/alienpackages.txt
 
 AMSGBAD3=""
 touch $WKGDIR/alienpackages.txt #create if doesn't exist.
 #remove an earlier entry, in case overriding (maybe earlier version)...
 apattern="s/${ANAMEONLY}//g"
 AVERONLY="`echo -n "$APKGNAME" | sed -e "$apattern"`"
 if [ "$AVERONLY" = "" ];then
  AMSGBAD3="
WARNING: FAULTY PACKAGE NAME $APKGNAME
         A package name should have a '-' followed by numeric digit
         to cleanly separate the version information.
         Example: abiword-0.5.6
         If later versions of the package are installed, previous
         package information will not be properly removed."
 else
  WPATTERN="^\"${ANAMEONLY}\-"
  cat $WKGDIR/alienpackages.txt | grep -v "$WPATTERN" > /tmp/tmpaliens
  sync
  mv -f /tmp/tmpaliens $WKGDIR/alienpackages.txt
 fi
 #create an entry in alienpackages.txt...
 #PET* variables are from the .specs file (see above)...
 echo -e "\"${APKGNAME}\" \"${APKGNAME}: ${PETMENUDESCR}\" on \" ${PETOFFICIALDEPS} \" \\" >> $WKGDIR/alienpackages.txt
 #create list of installed files...
 mv -f /tmp/${APKGNAME}.files $WKGDIR/${APKGNAME}.files
 sync

 #.desktop sanity check...
 AMSGBAD1="";AMSGBAD2=""
 ADESKTOPFILE="`cat $WKGDIR/${APKGNAME}.files | grep '\.desktop$' | head -n 1`"
 if [ ! "$ADESKTOPFILE" = "" ];then
  AEXEC="`cat $ADESKTOPFILE | grep '^Exec=' | cut -f 2 -d '='`"
  FAEXEC="bad"
  [ ! "`which $AEXEC`" = "" ] && [ -x $AEXEC ] && FAEXEC="okay"
  #this is for a really bad dotpup I came across, tries to execute an image file...
  [ ! "`echo -n "$AEXEC" | grep --extended-regexp 'xpm$|png$|jpg$|gif$'`" = "" ] && FAEXEC="bad"
  if [ "$FAEXEC" = "bad" ];then
   AMSGBAD1="
URGENT: FIX THIS! $AEXEC
        (specified in ${ADESKTOPFILE})
        is the executable launched from menu, but is incorrect."
  fi
  AICON="`cat $ADESKTOPFILE | grep '^Icon=' | cut -f 2 -d '='`"
  FAICON="bad"
  #get full path of icon...
  [ ! "`echo -n "$AICON" | cut -b 1`" = "/" ] && AICON="/usr/local/lib/X11/mini-icons/$AICON"
  #icon is bad if it is not 16x16...
  [ ! "`echo -n "$AICON" | grep '\.xpm$'`" = "" ] && TAICON="xpmtoppm"
  [ ! "`echo -n "$AICON" | grep '\.png$'`" = "" ] && TAICON="pngtopnm"
  [ ! "`echo -n "$AICON" | grep '\.gif$'`" = "" ] && TAICON="giftopnm"
  [ ! "`echo -n "$AICON" | grep '\.jpg$'`" = "" ] && TAICON="jpegtopnm"
  if [ "`$TAICON $AICON | pamfile | grep ' 16 by 16 '`" = "" ];then
   AMSGBAD2="
WARNING: FIX THIS!  $ICON 
         (specified in ${ADESKTOPFILE})
         used in menu is not 16x16, may mess-up rendering!"
  fi
 fi

 #dependency check code...
 yaf-splash -font "8x16" -outline 0 -margin 4 -bg orange -text "PETget package manager
Checking dependencies, please wait..." & #9x15B also looks okay.
 DEPSPID=$!
 dependcheckfunc #function to check dependencies.
 kill $DEPSPID
 AMSG2=""
 if [ -s /tmp/missinglibs.txt ];then
  #if [ "$FLAGDEPPKG" = "yes" ];then
  AMSG2="
IMPORTANT:
`cat /tmp/missinglibs.txt`

NOTE: Dependent packages shown without version numbers are official PETs:
click on desktop 'Install' icon to install these from the offical Puppy
PET repositories on the Internet. If a missing package has version number,
it is unofficial and you will need to download (from an 'unofficial' site)
then just click on it to install."
 fi

 #display a message that pkg installed, with useful info...
 AMSG="This application does NOT have a menu entry.
NOTE: Some DotPups create a menu entry in a special 'DotPups' location in the
menu, however this is no longer supported and if the DotPup install script
tries to create such an entry it is ignored. All .pet packages (and converted
DotPups) must now have a .desktop file."
 if [ ! "$ADESKTOPFILE" = "" ];then
  ACATEGORY="`cat $ADESKTOPFILE | grep '^Categories='  | cut -f 2 -d '=' | sed -e 's/.*;//g'`"
  APATTERN="[ ,]${ACATEGORY}"
  TOPMENU="`cat /etc/xdg/menus/hierarchy | grep "${APATTERN}" | cut -f 1 -d ' '`"
  AMENUDESCR="`cat $ADESKTOPFILE | grep '^Name=' | cut -f 2 -d '='`"
  AMSG="An entry has been created in the '${TOPMENU}' menu, with text
'${AMENUDESCR}'
HOWEVER, you need to restart the window manager to see it
(see 'Shutdown' or 'Window' menu)

NOTE:
If you want to know exactly what files have been installed, look
at /root/.packages/${APKGNAME}.files with a text editor."
 fi
# gxmessage -bg green -center -title "PETget package manager" "Package ${APKGNAME}.pet has been successfully installed.
#Note that this is a converted DotPup package, ${APKGNAME}.pup.
#
#${AMSG}
#${AMSG2}
#${AMSGBAD1}${AMSGBAD2}${AMSGBAD3}"
 DLG_REG7="
 <wtitle>PETget パッケージマネージャ</wtitle>
 <vbox>
  <pixmap><input file>/usr/local/lib/X11/pixmaps/ok.xpm</input></pixmap>
  <text><label>\"パッケージ ${APKGNAME}.pet のインストールに成功しました。
注意、これは変換された DotPup パッケージ ${APKGNAME}.pup です。

${AMSG}
${AMSG2}
${AMSGBAD1}${AMSGBAD2}${AMSGBAD3}\"</label></text>
  <text><label>\"  \"</label></text>
  <hbox>
   <button><input file>/usr/local/lib/X11/mini-icons/mini-tick.xpm</input><label>OKAY</label><action>EXIT:10</action></button>
  </hbox>
 </vbox>"
 echo "$DLG_REG7" | gtkdialog2 --stdin
 
 return 0
} #end installpupfunc

##livepackages.txt is the list of packages that can be installed or removed...
#if [ ! -f $WKGDIR/livepackages.txt ];then
# touch livepackages.txt
#fi
#created further down...

if [ -f $WKGDIR/alienpackages.txt ];then #IF2508
#v1.0.3 users may be installing alien packages, there is risk of alienpackages.txt getting
#wrongly formatted...
#correct format: "qhacc-3.3" "qhacc-3.3: Accounting" on "QT3APPS 3104K" \
#note, grep is looking for " \" but Ash firstly interpretes, then grep, so need ' \\\\'...
OKLINES="`cat $WKGDIR/alienpackages.txt | cut -f 7 -d '"' | grep ' \\\\' | wc -l`"
# ' need this to fix syntax highlighting in Geany.
ALLLINES="`cat $WKGDIR/alienpackages.txt | wc -l`"
if [ ! "$OKLINES" = "$ALLLINES" ];then
 if [ ! "$DISABLEDX" = "yes" ];then
  gxmessage -font "mono 14" -center -name "pet" -bg "#ff8080" -title "PETget package manager: エラー" " $WKGDIR/alienpackages.txt に初期化エラーがあります。
多分 alien package インストールスクリプトはファイルに不正なフォーマットで1行書き
加えられています。このファイルを視覚的に調べるたり原因となる
パッケージを見つけ出す事ができます。そして手動で修正できます。
そしてパッケージ製作者にインストールは障害がある事を報告して下さい。
-- これは不適切に作られた DotPup インストーラの場合に起こります。

alienpackages.txt のエントリは次のフォーマットでなければいけません:
\"QT3APPS 3104K\" の \"qhacc-3.3\" \"qhacc-3.3: Accounting\" \\
エントリはこの様に正確でなくてはいけません。フィールド間に余分な空白や
最後のバックスラッシュに続く引用符、空白もあってはいけません。空白行もなしです。
注意、最終行の終わりは「RETURN」が必要です。（これはテキストエディタの
カーソルが最終行に移動できるためです）

PETget パッケージマネージャを終了するには「OK」ボタンを押して下さい..."
 fi
 exit
fi
fi #IF2508

#clicked on a pet pkg, ask if want to install...
if [ ! "$COMMANDPKG" = "" ];then
 if [ "$CMD1STCHAR" = "/" ];then
  #difficult task, separate package name from version part... 
  #not perfect, some start with non-numeric version info...
  zPKGNAME="`basename "$ROXCMD" .pet`"
  NAMEONLY="`echo -n "$zPKGNAME" | sed -e 's/\-[0-9].*$//g'`"
  #...if that fails, do it the old way...
  [ "$NAMEONLY" = "$zPKGNAME" ] && NAMEONLY="`echo "$zPKGNAME" | cut -f 1 -d "-"`"
  QPATTERN="^${NAMEONLY}\\-"
  PRELABEL2=" "
  PRELABEL1="Welcome! You have chosen package $zPKGNAME"
  if [ ! "`ls -1 /root/.packages | grep "$QPATTERN"`" = "" ];then
   PRELABEL2="WARNING: Package '${NAMEONLY}' is already installed!"
  fi
  #v2.14 dlg to confirm install when clicked in rox...
  DLGQ="
 <wtitle>PETget package manager</wtitle>
 <vbox>
  <pixmap><input file>/usr/local/lib/X11/pixmaps/question.xpm</input></pixmap>
  <text><label>\"${PRELABEL1}\"</label></text>
  <text><label>\"${PRELABEL2}\"</label></text>
  <text><label>\" \"</label></text>
  <hbox>
   <button><input file>/usr/local/lib/X11/mini-icons/mini-tick.xpm</input><label>INSTALL PACKAGE</label><action>EXIT:10</action></button>
   <text><label>\" \"</label></text>
   <button><input file>/usr/local/lib/X11/mini-icons/mini-cross.xpm</input><label>ABORT INSTALL</label><action>EXIT:11</action></button>
  </hbox>
 </vbox>"
  RETVAL="`echo "$DLGQ" | gtkdialog2 --stdin | grep 'EXIT:' | cut -f 2 -d ':'`"
  [ ! "$RETVAL" = "10" ] && exit
 fi
fi

UNLEASHEDPKGS="`cat $WKGDIR/packages.txt`" #this is file from Unleashed.

#v2.14 livepackages.txt gets updated in rc.update, first creation here...
#um, rc.update now creates it, so this not necessary. but precaution...
if [ ! -f $WKGDIR/livepackages.txt ];then
 #livepackages.txt has all packages that were not installed by Unleashed...
 #this updates livepackages.txt when packages.txt is updated...
 #code here adds any new "off" packages from packages.txt to livepackages.txt...
 #note, backslash upsets newline char for piping, so escape it (shell and sed both)...
  touch  $WKGDIR/livepackages.txt
  cat  $WKGDIR/packages.txt | grep '" off "' >> /root/.packages/livepackages.txt
  sync
fi
#v2.14 if a bug and livepackages.txt gets emptied somehow, fix...
if [ ! -s $WKGDIR/livepackages.txt ];then
 #livepackages.txt is empty...
 #fill it up...
 cat  $WKGDIR/packages.txt | grep '" off "' >> /root/.packages/livepackages.txt
 sync
 #repair, turn on any installed official pkgs...
 for ONEFILE in `ls -1 $WKGDIR/*.files | tr '\n' ' '`
 do
  #turn entry on...
  APKGNAME="`basename $ONEFILE .files`"
  #escapes the '-' and '.' chars in pkg name...
  mAPKGNAME="`echo -n "$APKGNAME" | sed -e 's/\-/\\\-/g' | sed -e 's/\./\\\./g'`"
  #changes off to on...
  mPATTERN="s/\(^\"$mAPKGNAME\" \".*\"\) off \"/\1 on \"/g"
  cat $WKGDIR/livepackages.txt | sed -e "$mPATTERN" > /tmp/newlivepackages.txt
  sync
  mv -f /tmp/newlivepackages.txt $WKGDIR/livepackages.txt
 done
fi

if [ "$COMMANDPKG" = "" ];then #v1.0.5

 #v2.0.0
 RETVAL="`echo "$DLG1" | gtkdialog2 --stdin | grep 'EXIT:' | cut -f 2 -d ':'`"
 [ ! "$RETVAL" ] && RETVAL=19
 echo "RETVAL=$RETVAL"

else
 #noninteractive, install or remove a pkg.
 RETVAL=10
 #if have clicked on a .pet from Rox, is it an alien package?...
 if [ "$CMD1STCHAR" = "/" ];then
  #ROXCMD=/full/path/pkgname.pet
  YPATTERN="^\"`basename "$ROXCMD" .pet`\" "
  cat $WKGDIR/packages.txt | grep "$YPATTERN"
  [ $? -ne 0 ] && RETVAL=13 #0=found >0=not found. alien package.
 fi
fi

case $RETVAL in
 10) #continue script.
  PKGUNLEASHED="yes"
  ;;
 11) #check dependencies.
  cp -f ./livepackages.txt /tmp/zippidoodah.txt
  if [ -f ./alienpackages.txt ];then
   cat ./alienpackages.txt >> /tmp/zippidoodah.txt
  fi
  PKGSONLIST="`cat /tmp/zippidoodah.txt | grep '" on "'`"
  if [ ! "$PKGSONLIST" = "" ];then
   rm -f /tmp/rettags.txt
   echo '#!/bin/sh' > /tmp/pkgdialog
   echo 'RETTAGS="`Xdialog --title "PETget パッケージマネージャ: 依存性チェック" --left --stdout  --item-help --icon "/usr/local/lib/X11/pixmaps/packaging96.xpm" --no-cancel --no-tags --radiolist "依存性をチェックしたいパッケージ時を選択して下さい。\nこれは、必要なすべてのライブラリや依存パッケージが\nインストールされているかと言う事です..." 460x270+0+0 0 \' >> /tmp/pkgdialog
   echo "$PKGSONLIST" >> /tmp/pkgdialog
   echo ' `"' >> /tmp/pkgdialog
   echo 'if [ ! $? -eq 0 ];then' >> /tmp/pkgdialog
   echo ' exit'  >> /tmp/pkgdialog
   echo 'fi' >> /tmp/pkgdialog
   echo 'echo "$RETTAGS" > /tmp/rettags.txt' >> /tmp/pkgdialog
   sync #` geany fix.
   chmod 755 /tmp/pkgdialog
   /tmp/pkgdialog
   APKGNAME="`cat /tmp/rettags.txt 2> /dev/null`"
   if [ "$APKGNAME" = "" ];then
    exit
   fi
   yaf-splash -font "8x16" -outline 0 -margin 4 -bg orange -text "PETget package manager
Checking dependencies, please wait..." & #9x15B also looks okay.
   DEPSPID=$!
   dependcheckfunc #function.
   kill $DEPSPID
   if [ -s /tmp/missinglibs.txt ];then
    if [ "$FLAGDEPPKG" = "yes" ];then
     WARNLIB="IMPORTANT: It is recommended that you install the missing packages."
    else
     WARNLIB="The PETget package manager does not know what package/s has/have these libraries."
    fi
    if [ ! "$DISABLEDX" = "yes" ];then
     gxmessage -font "mono 14" -name "pet" -bg "#ff8080" -center -title "PETget: 依存性チェック 警告" "These dependencies required by $APKGNAME package are missing:
`cat /tmp/missinglibs.txt`

$WARNLIB"
    fi
   else
    if [ ! "$DISABLEDX" = "yes" ];then
     gxmessage -name "pet" -bg "green" -center -title "PETget: 依存性チェック OKAY" "It seems that all the dependencies required for this package are installed"
    fi
   fi
  fi
  exit
  ;;
 12)
  #exec mozilla http://www.puppylinux.org/wikka/DotPup
  exec dotpup
  ;;
 13) #Alien_package
  #ROXCMD is set if clicked on a .pet from Rox. Only comes here though
  #if the .pet is an alien package.
  if [ "$ROXCMD" = "" ];then #nothing on commandline.
   MSG9="PETget: Choose PET package"
   while [ 1 ];do
    #MU suggested add the 'tail -n 1'...
    ALIENFILE="`Xdialog --backtitle "注意: 拡張子が '.pet' のファイルを選択しなければいけません" --title "$MSG9" --stdout --no-buttons --fselect "/root/*" 0 0`"
    RETVAL=$?
    ALIENFILE="`echo -n "$ALIENFILE" | tail -n 1`"
    [ ! $RETVAL -eq 0 ] && exit
    [ -f $ALIENFILE ] && [ "`echo -n "$ALIENFILE" | grep -E '\.pet$|\.tar\.gz$'`" != "" ] && break
    MSG9="PETget: TRY AGAIN, Choose PET package, extension .pet"
   done
   sync
  else
   ALIENFILE="$ROXCMD"
  fi
  cp -af "$ALIENFILE" /root/.packages/ #copy, leave original.
  sync
  cd /root/.packages
  APKGNAMEEX="`basename $ALIENFILE`"
  #v2.13 test if enough space to expand tarball...
  #EXPFREEK=`df -k | grep ' /$' | tr -s ' ' | cut -f 4 -d ' '`
  EXPFREEB=`stat --filesystem --format=%f /` #no. free blocks.
  EXPFILEB=`stat --format=%b $APKGNAMEEX` #no. blocks.
  EXPNEEDB=`expr $EXPFILEB \* 3` #bz2 can expand up to x3,need twice temp space. v3.01 changed 5 to 3.
  if [ $EXPNEEDB -gt $EXPFREEB ];then
   if [ ! "$DISABLEDX" = "yes" ];then
    gxmessage -center -name "pet" -bg "#ff8080" -title "PETget: エラー" " $APKGNAMEEX パッケージは /root/.packages にダウンロードされています。
しかし解凍してインストールする空き容量が十分ではありません。
空きスペースは $EXPFREEB ブロックですが展開してインストール
するには一時的に $EXPNEEDB ブロックが必要です。

注意: pup_save.3fs 個人保存ファイルを使っている時は、
もっと大きくする必要があります -- 「ユーティリティ」メニューを参照。

このスクリプトはすぐにパッケージを削除して終了します..."
   fi
   echo "ERROR: Not enough free space."
   rm -f $APKGNAMEEX
   exit
  fi
  if [ ! "`echo "$APKGNAMEEX" | grep '\.pet$'`" = "" ];then
   pet2tgz $APKGNAMEEX
   APKGNAME="`echo "$APKGNAMEEX" | sed -e 's/\.pet$//g'`"
   APKGNAMEEX="${APKGNAME}.tar.gz"
  fi
  if [ ! "`echo "$APKGNAMEEX" | grep --extended-regexp "\.tgz$|\.tar\.gz$"`" = "" ];then
   #v2.13 '--absolute-names' needed for openoffice tarball to fix extraction error.
   tar --absolute-names -zxf $APKGNAMEEX
   APKGNAME="`echo "$APKGNAMEEX" | sed -e 's/\.tgz$//g' | sed -e 's/\.tar\.gz//g'`"
  fi
  if [ ! "`echo "$APKGNAMEEX" | grep --extended-regexp "\.tbz2$|\.tar\.bz2$"`" = "" ];then
   tar -jxf $APKGNAMEEX
   APKGNAME="`echo "$APKGNAMEEX" | sed -e 's/\.tbz2$//g' | sed -e 's/\.tar\.bz2$//g'`"
  fi
  if [ ! -d ./$APKGNAME ];then
   if [ ! "$DISABLEDX" = "yes" ];then
    gxmessage -font "mono 14" -center -name "pet" -bg "#ff8080" -title "PETget: パッケージ展開エラー" "パッケージ $APKGNAMEEX を展開中エラーがありました。
ファイルが破損したかそのディレクトリに（大部分のパッケージが展開される）
 $APKGNAME/ と言う名前で展開されませんでした。
 /root/.packages/ ディレクトリに行き、手動で片付けなければなりません。

このスクリプトはこれで終了します..."
   fi
   exit
  fi
  #v2.14 tgz2pet will embed a slackware-style binary tarball inside a directory
  #named APKGNAME, as the tarball expands direct to /...
  if [ -f $WKGDIR/$APKGNAME/${APKGNAME}.tar.gz ];then #tgz2pet also renames .tgz
   cd $WKGDIR/$APKGNAME/
   tar --absolute-names -zxf ./${APKGNAME}.tar.gz
   sync
   rm -f  ./${APKGNAME}.tar.gz
   cd $WKGDIR
  fi
  #v2.14 pup2pet converts .pup to .pet by embedding inside tarball...
  if [ -f $WKGDIR/$APKGNAME/${APKGNAME}.pup ];then #pup2pet created this.
   rm -f $WKGDIR/$APKGNAME.tar.gz
   installpupfunc #function call.
   rm -rf $WKGDIR/$APKGNAME
   exit
  fi

  #difficult task, separate package name from version part... 
  #not perfect, some start with non-numeric version info...
  ANAMEONLY="`echo -n "$APKGNAME" | sed -e 's/\-[0-9].*$//g'`"
  #...if that fails, do it the old way...
  [ "$ANAMEONLY" = "$APKGNAME" ] && ANAMEONLY="`echo "$APKGNAME" | cut -f 1 -d "-"`"

  APATTERN="s/.\/$APKGNAME//g"
  #need to find regular files and links separately...
  find ./$APKGNAME -type f -mount -mindepth 2 | sed -e "$APATTERN" | sed -e 's/\/root0\//\/root\//g' > ./$APKGNAME.files
  sync
  find ./$APKGNAME -type l -mount -mindepth 2 | sed -e "$APATTERN" | sed -e 's/\/root0\//\/root\//g' >> ./$APKGNAME.files
  sync

   #go ahead and install it...
#   gxmessage -borderless -font "DejaVu Sans 14" -center -bg "orange" -title "PETget" -buttons "" " PETget package manager
# Processing, please wait..." &
   installpkgfunc #function call.

   touch $WKGDIR/alienpackages.txt #create if doesn't exist.
   #remove an earlier entry, in case overriding (maybe earlier version)...
   WPATTERN="^\"${ANAMEONLY}\-"
   cat $WKGDIR/alienpackages.txt | grep -v "$WPATTERN" > /tmp/tmpaliens
   sync
   mv -f /tmp/tmpaliens $WKGDIR/alienpackages.txt
   #create an entry in alienpackages.txt...
   #PET* variables are from the .specs file (see above)...
   echo -e "\"${APKGNAME}\" \"${APKGNAME}: ${PETMENUDESCR}\" on \" ${PETOFFICIALDEPS} \" \\" >> $WKGDIR/alienpackages.txt

  exit
  # " Geany needs this!
  ;;
 *)
  exit
  ;;
esac

if [ ! "$DISABLEDX" = "yes" ];then
 yaf-splash -font "8x16" -outline 0 -margin 4 -bg orange -text "PETget package manager
Processing, please wait..." &
 PLEASEMSG=$!
fi

##on the other hand, if livepackages.txt has an off pkg that is no longer in
##packages.txt, remove it... (may happen at a version upgrade)
#echo -n "" > /tmp/livepackages-step2.txt
#cat $WKGDIR/livepackages.txt | sed -e 's/\\/\\\\/g' |
#while read HEAD1ST
#do
# if [ "`echo -n "$HEAD1ST" | grep '" on "'`" = "" ];then #off pkgs
#  APKGNAME="`echo "$HEAD1ST" | cut -f 2 -d '"'`" #'geany fix.
#  APKGNAME="^\"$APKGNAME\""
#  [ ! "`cat $WKGDIR/packages.txt | grep "$APKGNAME"`" = "" ] && echo "$HEAD1ST" >> /tmp/livepackages-step2.txt
# else #on pkgs
#  echo "$HEAD1ST" >> /tmp/livepackages-step2.txt
# fi
#done
#sync
#mv -f /tmp/livepackages-step2.txt $WKGDIR/livepackages.txt

##...one thing though. this script is not going to be too happy if user changes iso 'flavours'.
##we need some 'clash' checking...
##if "on" in packages.txt and listed in livepackages.txt, then remove, but if pet pkg installed
##then need to uninstall it... (whew)...
#rm -f /tmp/forcepkgremove.txt 2>/dev/null
#ONPKGS="`echo "$UNLEASHEDPKGS" | grep '" on "'`"
#echo "$ONPKGS" | sed -e 's/\\/\\\\/g' |
#while read HEAD1ST
#do
# APKGNAME="`echo "$HEAD1ST" | cut -f 2 -d '"'`" #'geany fix.
# APKGNAME="^\"$APKGNAME\""
# #remove $APKGNAME line from livepackages.txt...
# #remove version number...
# #NAMETITLE="`echo "$APKGNAME" | cut -f 1 -d "-"`" #format is ^\"name
# #v2.14 no, do it this way...
# #difficult task, separate package name from version part... 
# #not perfect, some start with non-numeric version info...
# NAMETITLE="`echo -n "$APKGNAME" | sed -e 's/\-[0-9].*$//g'`"
# #...if that fails, do it the old way...
# [ "$NAMETITLE" = "$APKGNAME" ] && NAMETITLE="`echo "$APKGNAME" | cut -f 1 -d "-"`"
#
# NAMETITLE="${NAMETITLE}\-"
# WRONGPKG="`cat $WKGDIR/livepackages.txt | grep "$NAMETITLE"`"
# if [ ! "$WRONGPKG" = "" ];then
#  if [ ! "`echo "$WRONGPKG" | grep '" on "'`" = "" ];then
#   #but, there's a problem, as this pet package is installed...
#   echo "$WRONGPKG" >> /tmp/forcepkgremove.txt
#  fi
#  #now remove the line...
#  cat $WKGDIR/livepackages.txt | grep -v "$NAMETITLE" > /tmp/livepackages.txt
#  sync
#  mv -f /tmp/livepackages.txt $WKGDIR/livepackages.txt #mv -f gives Busybox error! ...now using full mv.
#  sync
# fi
#done

#if [ -f /tmp/forcepkgremove.txt ];then
# if [ ! "$DISABLEDX" = "yes" ];then
#  gxmessage -font "mono 14" -name "pet" -bg "#ff8080" -center -title "PETget: PACKAGE CLASH" "
#WARNING: These packages were previously installed by PETget:
#`cat /tmp/forcepkgremove.txt | cut -f 1 -d " " | tr "\n" " "`
#
#HOWEVER, they are also in the live-CD ISO (or pup_${PUPPYVERSION}.sfs in case
#of other installations). This is a clash, and this script will now
#force their removal. You may need to reboot for these packages on
#the live-CD to be reinstated.
#Note: the next 2-pane window will not show them, as they are now
#      scheduled for automatic removal after the 2-pane window OK
#      button is pressed. PLEASE DO NOT ABORT PETget IN ANY FOLLOWING
#      WINDOW -- PRESS OK BUTTON IN NEXT WINDOW AND ALLOW SCRIPT TO
#      COMPLETE, SO THAT IT CAN REMOVE THESE OFFENDING PACKAGES --
#      ABORTING NOW WILL STUFF THINGS UP!
#
#Click OK to continue script..."
# fi
#fi

##need to do the same clash checking for alien packages...
#rm -f /tmp/forcealienpkgremove.txt 2>/dev/null
#ONPKGS="`echo "$UNLEASHEDPKGS" | grep '" on "'`"
#echo "$ONPKGS" | sed -e 's/\\/\\\\/g' |
#while read HEAD1ST
#do
# APKGNAME="`echo "$HEAD1ST" | cut -f 2 -d '"'`" #' geany fix.
# APKGNAME="^\"$APKGNAME\""
# #remove $APKGNAME line from alienpackages.txt...
# #remove version number...
# #NAMETITLE="`echo "$APKGNAME" | cut -f 1 -d "-"`" #format is ^\"name
# #v2.14 no, do it this way...
# #difficult task, separate package name from version part... 
# #not perfect, some start with non-numeric version info...
# NAMETITLE="`echo -n "$APKGNAME" | sed -e 's/\-[0-9].*$//g'`"
# #...if that fails, do it the old way...
# [ "$NAMETITLE" = "$APKGNAME" ] && NAMETITLE="`echo "$APKGNAME" | cut -f 1 -d "-"`"
#
# NAMETITLE="${NAMETITLE}\-"
# WRONGPKG="`cat $WKGDIR/alienpackages.txt 2> /dev/null | grep "$NAMETITLE"`"
# if [ ! "$WRONGPKG" = "" ];then
#  if [ ! "`echo "$WRONGPKG" | grep '" on "'`" = "" ];then
#   #but, there's a problem, as this package is installed...
#   echo "$WRONGPKG" >> /tmp/forcealienpkgremove.txt
#  fi
#  #now remove the line...
#  cat $WKGDIR/alienpackages.txt 2> /dev/null | grep -v "$NAMETITLE" > /tmp/alienpackages.txt
#  sync
#  mv -f /tmp/alienpackages.txt $WKGDIR/alienpackages.txt #mv -f gives Busybox error! ...now using full mv.
#  sync
# fi
#done

#if [ -f /tmp/forcealienpkgremove.txt ];then
# if [ ! "$DISABLEDX" = "yes" ];then
#  gxmessage -font "mono 14" -name "pet" -bg "#ff8080" -center -title "PETget: PACKAGE CLASH" "WARNING: These alien packages were previously installed, either by PETget,
#or by some other means registered with PETget upon installation:
#`cat /tmp/forcealienpkgremove.txt | cut -f 1 -d " " | tr "\n" " "`
#
#HOWEVER, they are also in the live-CD ISO (or pup_${PUPPYVERSION}.sfs in case
#of other installations). This is a clash, and this script will now
#force their removal. You may need to reboot for these packages on
#the live-CD to be reinstated.
#Note: the next 2-pane window will not show them, as they are now
#      scheduled for automatic removal after the 2-pane window OK
#      button is pressed. PLEASE DO NOT ABORT PETget IN ANY FOLLOWING
#      WINDOW -- PRESS OK BUTTON IN NEXT WINDOW AND ALLOW SCRIPT TO
#      COMPLETE, SO THAT IT CAN REMOVE THESE OFFENDING PACKAGES --
#      ABORTING NOW WILL STUFF THINGS UP!
#
#Click OK to continue script..."
# fi
# cat /tmp/forcealienpkgremove.txt >> /tmp/forcepkgremove.txt
# sync
#fi


sort -u $WKGDIR/livepackages.txt > /tmp/livepackages.txt
sync
PACKAGESFND="`cat /tmp/livepackages.txt`"

cp -f $WKGDIR/livepackages.txt /tmp/zippidoodah.txt
sync
if [ -f $WKGDIR/alienpackages.txt ];then
 #v1.0.3 problem, could have gimp-2.0.6 off in livepackages.txt but on in alienpackages.txt
 #we don't want both lines, we only want the last line...
 ALIENONPKGS="`cat $WKGDIR/alienpackages.txt | grep '" on "' | cut -f 2 -d '"'`" # ' grrr, Geany again!
 for ONEONALIEN in $ALIENONPKGS
 do
  FPATTERN="^\"${ONEONALIEN}\" "
  cat /tmp/zippidoodah.txt | grep -v "$FPATTERN" > /tmp/templive.txt
  sync
  mv -f /tmp/templive.txt /tmp/zippidoodah.txt
 done
 sync
 cat $WKGDIR/alienpackages.txt >> /tmp/zippidoodah.txt
fi
sync

#this is the list of all pet/alien pkgs. 'on' if installed, 'off' if not...
ALLPKGSFND="`cat /tmp/zippidoodah.txt`"

[ ! "$DISABLEDX" = "yes" ] && kill $PLEASEMSG #killall xmessage

if [ "$COMMANDPKG" = "" ];then #IF2508 v1.0.5 
rm -f /tmp/rettags.txt
echo '#!/bin/sh' > /tmp/pkgdialog
echo 'RETTAGS="`Xdialog --title "PETget パッケージマネージャ" --left --stdout --separator " "  --item-help --icon "/usr/local/lib/X11/pixmaps/pet48.png" --ok-label "OKAY" --cancel-label "中止" --buildlist "パピーにパッケージの追加や取り外しができます。追加を選択したどんなパッケージも、\nインターネットからダウンロードする事もローカルから得る事も選べます。\n左側の窓にはインストールできる公式パッケージがあります。右側の窓は\nインストール済みの（公式、非公式）パッケージの一覧です。\nパッケージの上にマウスをのせると詳しい情報が出ます。" 780x540+0+0 0 \' >> /tmp/pkgdialog
echo "$ALLPKGSFND" >> /tmp/pkgdialog
echo ' `"' >> /tmp/pkgdialog
echo 'if [ ! $? -eq 0 ];then' >> /tmp/pkgdialog
echo ' exit'  >> /tmp/pkgdialog
echo 'fi' >> /tmp/pkgdialog
echo 'echo "$RETTAGS" > /tmp/rettags.txt' >> /tmp/pkgdialog

# ` #fix highlighting for Geany.
sync
chmod 755 /tmp/pkgdialog
/tmp/pkgdialog
else #v1.0.5
 #noninteractive mode. COMMANDPKG has name of pkg to be added or removed.
 ALLONNAMES="`echo -n "$ALLPKGSFND" | grep '" on "' | cut -f 2 -d '"'`" #' geany fix.
 if [ "`echo -n "$COMMANDPKG" | cut -b 1`" = '+' ];then
  ADDONENAME="`echo "$COMMANDPKG" | cut -b 2-99`"
  ALLONNAMES="$ALLONNAMES $ADDONENAME"
 fi
 if [ "`echo "$COMMANDPKG" | cut -b 1`" = '-' ];then
  REMONENAME="`echo "$COMMANDPKG" | cut -b 2-99`"
  ALLONNAMES="`echo -n "$ALLONNAMES" | grep -v "$REMONENAME"`"
 fi
 echo -n "$ALLONNAMES" | tr "\n" " " > /tmp/rettags.txt
fi #IF2508

if [ ! -f /tmp/rettags.txt ];then
 exit
fi

yaf-splash -font "8x16" -outline 0 -margin 4 -bg orange -text "PETget package manager
Processing, please wait..." &
TAGSPID=$!

#/tmp/rettags.txt has all the tags (package names) chosen to be in Puppy.
#status field to "on", otherwise "off"...
#PACKAGESFND is the updated contender for livepackages.txt.
RETTAGS=" `cat /tmp/rettags.txt` "
#v2.14 only update livepackages.txt after a pkg actually installed or
#removed. but need to update now for determining what to install/remove...
echo -n "" > /tmp/plannedlivepackages.txt
echo "$PACKAGESFND" | sed -e 's/\\/\\\\/g' |
while read HEAD1ST
do
 APKGNAME="`echo "$HEAD1ST" | cut -f 2 -d '"'`" #' geany fix.
 EPATTERN=" ${APKGNAME} "
 if [ "`echo -n "$RETTAGS" | grep "${EPATTERN}"`" = "" ];then
  #make sure it is off...
  echo "$HEAD1ST" | sed -e 's/\" on \"/\" off \"/g' >> /tmp/plannedlivepackages.txt
 else
  #make sure it is on...
  echo "$HEAD1ST" | sed -e 's/\" off \"/\" on \"/g' >> /tmp/plannedlivepackages.txt
 fi
done
sync

echo
#now to find out which packages are to be installed or uninstalled...
#WARNING: packages.txt must not have a ">" character in it!
PKGSCHGD="`echo "$PACKAGESFND" | diff -B - /tmp/plannedlivepackages.txt | grep -v "\-\-\-" | grep '>' | cut -b 3-256`"
PKGS2ADD="`echo "$PKGSCHGD" | grep '" on "'`"
PKGS2REM="`echo "$PKGSCHGD" | grep '" off "'`"
rm -f /tmp/plannedlivepackages.txt

#if [ -f /tmp/forcepkgremove.txt ];then
# if [ "$PKGS2REM" = "" ];then
#  PKGS2REM="`cat /tmp/forcepkgremove.txt`"
# else
#  PKGS2REM="$PKGS2REM
#`cat /tmp/forcepkgremove.txt`"
# fi
#fi

#also handle alien package removal...
RETTAGS=" `cat /tmp/rettags.txt` "
if [ -f $WKGDIR/alienpackages.txt ];then
 echo "$PKGS2REM" > /tmp/pkgs2rem.txt
 cat $WKGDIR/alienpackages.txt | sed -e 's/\\/\\\\/g' |
 while read HEAD1ST
 do
  APKGNAME="`echo "$HEAD1ST" | cut -f 2 -d '"'`"  # ' Geany needs this.
  EPATTERN=" ${APKGNAME} "
  BPATTERN="^\"${APKGNAME}\" "
  if [ "`echo -n "$RETTAGS" | grep "${EPATTERN}"`" = "" ];then
   if [ "$PKGS2REM" = "" ];then
    PKGS2REM="`cat $WKGDIR/alienpackages.txt | grep "$BPATTERN"`"
   else
    PKGS2REM="$PKGS2REM
`cat $WKGDIR/alienpackages.txt | grep "$BPATTERN"`"
   fi
#   #delete entry...
#   cat $WKGDIR/alienpackages.txt | grep -v "$BPATTERN" > /tmp/alienpackages.txt
#   sync
#   mv -f /tmp/alienpackages.txt $WKGDIR/alienpackages.txt
  fi
  echo "$PKGS2REM" > /tmp/pkgs2rem.txt #as currently in separate process.
 done
 sync
 PKGS2REM="`cat /tmp/pkgs2rem.txt`"
fi

#how to uninstall?
#how to install?
#the working directory is /root/.packages/, i think will expand a package here first, extract a filelist,
#then move it to destination...

kill $TAGSPID

###########################PKGS2REM###################
if [ ! "$PKGS2REM" = "" ];then
 #v1.0.3 hiccup, see patch above, it is possible we can get duplicate entries here, if a pkg
 #is listed in both alienpackages.txt and livepackages.txt. use sort...
 PKGREMNAMES="`echo "$PKGS2REM" | cut -f 1 -d " " | sort -u | tr "\n" " "`"
 if [ ! "$DISABLEDX" = "yes" ];then
# gxmessage -center -name "pet" -bg "orange" -buttons "REMOVE:10,ABORT:11" "You have chosen to remove these packages from Puppy:
#$PKGREMNAMES
#
#Click REMOVE button to remove them...
#Click ABORT to exit from PETget package manager..."
#  if [ $? -ne 10 ];then

  xPKGREMNAMES="`echo -n "$PKGREMNAMES" | tr '"' "'"`"
  DLG_REM1="
 <wtitle>PETget パッケージマネージャ</wtitle>
 <vbox>
  <pixmap><input file>/usr/local/lib/X11/pixmaps/question.xpm</input></pixmap>
  <text><label>パピーから次のパッケージを削除をするよう選択されました:</label></text>
  <text><label>$xPKGREMNAMES</label></text>
  <text><label>\"  \"</label></text>
  <hbox>
   <button><input file>/usr/local/lib/X11/mini-icons/mini.checkmark.xpm</input><label>これを削除</label><action>EXIT:10</action></button>
   <text><label>\" \"</label></text>
   <button><input file>/usr/local/lib/X11/mini-icons/mini-cross.xpm</input><label>削除を中止</label><action>EXIT:11</action></button>
  </hbox>
 </vbox>
"
  RETVAL="`echo "$DLG_REM1" | gtkdialog2 --stdin | grep 'EXIT:' | cut -f 2 -d ':'`"
  if [ ! "$RETVAL" = "10" ];then
#  restorefunc
  exit
 fi
#  gxmessage -borderless -font "DejaVu Sans 14" -center -bg "orange" -title "PETget" -buttons "" " PETget package manager
# 
# Processing, please wait..." &
#  yaf-splash -font "8x16" -outline 0 -margin 4 -bg orange -text "PETget package manager
#Processing, please wait..." &
#  MSGPID=$!
 fi

# #v1.0.6 if remove a w.m., leave its menu config file behind...
#     cp -f /root/.fvwm95rc /tmp/fvwm95rcBACKUP
#     cp -f /root/.jwmrc /tmp/jwmrcBACKUP
#     cp -f /root/.icewm/menu /tmp/icemenuBACKUP

 echo "$PKGS2REM" | sed -e 's/\\/\\\\/g' |
 while read HEAD1ST #WHILE-103A
 do
  yaf-splash -font "8x16" -outline 0 -margin 4 -bg orange -text "PETget package manager
Processing, please wait..." &
  MSGPID=$!
  APKGNAME="`echo "$HEAD1ST" | cut -f 2 -d '"'`"   # ' Geany needs this.
  QAPKGNAMEQ="^\"${APKGNAME}\""
  #$APKGNAME.files has the file list for the package...
  if [ -f $WKGDIR/$APKGNAME.files ];then #103B

   #v2.14 dunno why, this causes the do-loop to exit after first loop
   # (if there are multiple pkgs to remove)...
   ##remove any entries in the master help index...
   #/usr/sbin/indexgen.sh remove $WKGDIR/$APKGNAME.files

   #v1.0.6 do not remove w.m. menu config files...
   cat $WKGDIR/$APKGNAME.files | grep -v "\\.icewm/menu" | grep -v "\\.jwmrc" | grep -v "\\.fvwm95rc" > /tmp/removefileslist.txt
   sync
   cp -f /tmp/removefileslist.txt $WKGDIR/$APKGNAME.files
   FDESK=""
   for ONEFILE in `cat ./$APKGNAME.files`
   do
    #v2.14 if there is a .desktop file, then need to regenerate the menu...
    [ ! "`echo -n "$ONEFILE" | grep '\.desktop$'`" = "" ] && FDESK="$ONEFILE"
    #.files file may be malformed. check entry is a genuine file...
    #v2.11 some symlinks may not get removed. '-e' will not work if symlink
    #is pointing to a non-existent file. So, check for symlink...
    REMFILE=""
    [ -h $ONEFILE ] && REMFILE="yes"
    [ -e $ONEFILE ] && REMFILE="yes"
    if [ "$REMFILE" = "yes" ];then
     if [ ! -d $ONEFILE ];then
      #v2.0.0
      if [ -e /initrd/pup_ro2$ONEFILE ];then
       #the problem is, deleting the file on the top layer places a ".wh" whiteout file,
       #that hides the original file. what we want is to remove the installed file, and
       #restore the original pristine file...
       cp -af /initrd/pup_ro2$ONEFILE $ONEFILE
      else
       rm -f $ONEFILE
      fi
      #v2.0.0 also, delete empty dirs...
      DELDIR="`dirname $ONEFILE`"
      [ "`ls -1 $DELDIR`" = "" ] && rmdir $DELDIR
     fi
    fi
   done
   #v2.11 go through again and remove any empty dirs...
   #note, it is done above, but is incomplete. this should catch the rest...
   for ONEFILE in `cat ./$APKGNAME.files`
   do
    DELDIR="`dirname $ONEFILE`"
    [ -d $DELDIR ] && [ "`ls -1 $DELDIR`" = "" ] && rmdir $DELDIR
    #check one level up... but do not delete top dir, like /opt...
    DELLEVELS=`echo -n "$DELDIR" | sed -e 's/[^/]//g' | wc -c | sed -e 's/ //g'`
    if [ $DELLEVELS -gt 2 ];then
     DELDIR="`dirname $DELDIR`"
     [ -d $DELDIR ] && [ "`ls -1 $DELDIR`" = "" ] && rmdir $DELDIR
    fi
   done
   if [ -f ./$APKGNAME.remove ];then
    ./$APKGNAME.remove
   fi
   #if [ -f ./$APKGNAME.keyword ];then
   # #code here to remove menu entries etc...
   # #if it's a forced removal, due to same package existing in live-cd, don't want to
   # #remove from menus...
   # CPATTERN="\"${APKGNAME}\""
   # if [ "`cat /tmp/forcepkgremove.txt | grep "$CPATTERN"`" = "" ];then
   #   AKEYWORD="`cat ./$APKGNAME.keyword`"
   #   #v1.0.5
   #   /usr/sbin/fixmenus /root \-$AKEYWORD
   # fi
   #fi
   [ ! "$FDESK" = "" ] && /usr/sbin/fixmenus #v2.14
   rm -f ./$APKGNAME.*
   
   #v2.14 turn it off if an entry in livepackages.txt...
   #escapes the '-' and '.' chars in pkg name...
   mAPKGNAME="`echo -n "$APKGNAME" | sed -e 's/\-/\\\-/g' | sed -e 's/\./\\\./g'`"
   #changes on to off...
   mPATTERN="s/\(^\"$mAPKGNAME\" \".*\"\) on \"/\1 off \"/g"
   cat ./livepackages.txt | sed -e "$mPATTERN" > /tmp/newlivepackages.txt
   sync
   mv -f /tmp/newlivepackages.txt ./livepackages.txt

   #v2.14 delete entry if in alienpackages.txt...
   cat $WKGDIR/alienpackages.txt | grep -v "$QAPKGNAMEQ" > /tmp/alienpackages.txt
   sync
   mv -f /tmp/alienpackages.txt $WKGDIR/alienpackages.txt

   if [ ! "$DISABLEDX" = "yes" ];then
    kill $MSGPID
#    gxmessage -name "pet" -bg "#80ff80" -center -title "PETget" "SUCCESS: $APKGNAME is removed!
#
#Note: After exiting from PETget, it is recommended that you reboot
#      Puppy to fully remove all traces of the uninstalled package."
    DLG_REM2="
 <wtitle>PETget パッケージマネージャ</wtitle>
 <vbox>
  <pixmap><input file>/usr/local/lib/X11/pixmaps/ok.xpm</input></pixmap>
  <text><label>\"成功: ${APKGNAME} は削除されました！

注意: PETget 終了後、アンインストールしたパッケージの
         すべての跡を完全に削除するにはパピーを再起動する
         必要があります。\"</label></text>
  <text><label>\"  \"</label></text>
  <hbox>
   <button><input file>/usr/local/lib/X11/mini-icons/mini-tick.xpm</input><label>OKAY</label><action>EXIT:10</action></button>
  </hbox>
 </vbox>"
     echo "$DLG_REM2" | gtkdialog2 --stdin
   fi
   sync
  fi #103B
  #kill $MSGPID 2>/dev/null
 done #WHILE-103A

# #v1.0.6 now restore w.m. config files...
#     cp -f /tmp/fvwm95rcBACKUP /root/.fvwm95rc
#     cp -f /tmp/jwmrcBACKUP /root/.jwmrc
#     cp -f /tmp/icemenuBACKUP /root/.icewm/menu

# if [ ! "$DISABLEDX" = "yes" ];then
#  kill $MSGPID #killall xmessage
# fi
fi

##################PKGS2ADD########################
while [ ! "$PKGS2ADD" = "" ];do #WHILE-PKGS2ADD
 echo -n "" > /tmp/missingpkgs.txt
 PKGADDNAMES="`echo "$PKGS2ADD" | cut -f 1 -d " " | tr "\n" " "`"
 STARTMSG=""
 BKCOLOR="orange"
 while [ 1 ];do
  #check if invoked from rox...
  if [ ! "$ROXCMD" = "" ];then
   RPATTERN="\"`basename "$ROXCMD" .pet`\""
   if [ ! "`echo -n "$PKGADDNAMES" | grep "$RPATTERN"`" = "" ];then
    if [ "`echo -n "$ROXCMD" | grep --extended-regexp '^ftp|^http'`" = "" ];then
     cp -f "$ROXCMD" /root/.packages/
     PETFILE="`basename "$ROXCMD"`"
     #pet2tgz /root/.packages/$PETFILE #convert .pet to .tar.gz.
     #if [ $? -ne 0 ];then #failed.
     # gxmessage -center -name "pet" -bg "red" -title "PETget: ERROR" "It seems that the file $PETFILE is corrupted. Cannot install."
     # rm -f /root/.packages/$PETFILE 2>/dev/null
     # rm -f /root/.packages/${COMMANDPKG}.tar.gz 2>/dev/null
     # restorefunc
     # exit
     #fi
     PKGSRC="." #tells code further down that pkg already in .packages.
    else
     PKGSRC="`dirname $ROXCMD`" #url
    fi 
    RETVAL=99
    break
   fi 
  fi
#  gxmessage -center -name "pet" -bg "$BKCOLOR" -title "PETget" -buttons "ibiblio.org:10,nluug.nl:11,gatech.edu:12,Local:19,ABORT:20" "${STARTMSG}You have chosen to install these packages in Puppy:
#$PKGADDNAMES
#
#Please connect to the Internet then press a button to choose download site.
#If you click on \"Local\" button, the packages must already be downloaded,
#that is, somewhere local."
#  RETVAL=$?
  xPKGADDNAMES="`echo -n "$PKGADDNAMES" | tr '"' "'"`"
  DLG_INST1="
 <wtitle>PETgetパッケージマネージャ</wtitle>
 <vbox>
  <pixmap><input file>/usr/local/lib/X11/pixmaps/pet48.png</input></pixmap>
  <text><label>\"${STARTMSG}次のパッケージをパピーにインストールするよう選択されました:
$xPKGADDNAMES

インターネットに接続してダウンロードサイトの選択ボタンを押して下さい。
「ローカル」ボタンをクリックするには、パッケージはすでにローカルの
どこかにダウンロードされている必要があります。\"</label></text>
  <text><label>\"  \"</label></text>
  <hbox>
   <button><label>ibiblio.org</label><action>EXIT:10</action></button>
   <button><label>nluug.nl</label><action>EXIT:11</action></button>
   <button><label>gatech.edu</label><action>EXIT:12</action></button>
   <button><label>ローカル</label><action>EXIT:19</action></button>
   <button><label>中止</label><action>EXIT:20</action></button>
  </hbox>
 </vbox>"
  RETVAL=`echo "$DLG_INST1" | gtkdialog2 --stdin | grep 'EXIT:' | cut -f 2 -d ':'`

  WWWSITE=""
  [ $RETVAL -eq 10 ] && WWWSITE="ibiblio.org"
  [ $RETVAL -eq 11 ] && WWWSITE="ftp.nluug.nl"
  [ $RETVAL -eq 12 ] && WWWSITE="cc.gatech.edu"
  if [ ! "$WWWSITE" = "" ];then
    ping -c 1 -q $WWWSITE
    if [ ! $? -eq 0 ];then
     #v1.0.5 GuestToo has suggested another test...
     if wget -t 2 -T 20 --waitretry=20 --spider -S $WWWSITE -o /dev/stdout | grep '200 OK'
     then
      echo "$WWWSITE is online"
     else
      BKCOLOR="#FF8080"
      STARTMSG="ERROR: $WWWSITE IS UNREACHABLE!
...are you connected to the Internet?
...maybe that site is down? Try another.

"
      continue
     fi
    fi
  fi
  break
 done
 case $RETVAL in
 10)
  #PKGSRC="ftp://ibiblio.org/pub/Linux/distributions/puppylinux/puppy-${RIGHTVER}/packages"
  #PKGSRC="ftp://ibiblio.org/pub/Linux/distributions/puppylinux/pet_packages"
  #v2.10...
  PKGSRC="http://distro.ibiblio.org/pub/linux/distributions/puppylinux"
  #...left off 'pet_packages' directory as will test below.
  ;;
 11)
  #PKGSRC="http://ftp.nluug.nl/ftp/pub/os/Linux/distr/puppylinux/puppy-${RIGHTVER}/packages"
  PKGSRC="http://ftp.nluug.nl/ftp/pub/os/Linux/distr/puppylinux"
  #...left off 'pet_packages' directory as will test below.
  ;;
 12)
  PKGSRC="ftp://ftp.oss.cc.gatech.edu/pub/linux/distributions/puppylinux"
  ;;
 19) #Local
  LOCALDIR="/root"
  if [ -s /var/log/petlocaldir ];then
   OLDLOCALDIR="`cat /var/log/petlocaldir`"
   [ -d $OLDLOCALDIR ] && LOCALDIR="$OLDLOCALDIR"
  fi
  LOCALDIR="`Xdialog --backtitle "注意: ファイルは表示されません、ディレクトリだけです" --title "PupGet: ローカルディレクトリの選択" --stdout --no-buttons --dselect "$LOCALDIR" 0 0`"
  if [ ! $? -eq 0 ];then
#   restorefunc
   exit
  fi
  sync
  [ ! "$LOCALDIR" = "" ] && echo "$LOCALDIR" > /var/log/petlocaldir
  KEEPGOING="no"
  for ONEFILE in `echo "$PKGS2ADD" | cut -f 2 -d '"' | tr "\n" " "`
  do
   PETFND="no"
   if [ -f ${LOCALDIR}/${ONEFILE}.pet ];then
    cp -af ${LOCALDIR}/${ONEFILE}.pet /root/.packages/
    PETFND="yes"
   fi
   #legacy .tar.gz support...
   if [ -f ${LOCALDIR}/${ONEFILE}.tar.gz ];then
    cp -af ${LOCALDIR}/${ONEFILE}.tar.gz /root/.packages/
    PETFND="yes"
   fi
   if [ "$PETFND" = "no" ];then
    gxmessage -font "mono 14" -center -name "pet" -bg "#ff8080" -title "PETget: ローカルパッケージエラー" "
エラー:  ${ONEFILE}.pet ファイルは $LOCALDIR フォルダにありません"
   else
    KEEPGOING="yes" #want to keep going even if only found one pkg.
   fi
   sync
   [ -f /root/.packages/${ONEFILE}.pet ] && pet2tgz /root/.packages/${ONEFILE}.pet
  done
  #keep going even if found one pkg...
  if [ "$KEEPGOING" = "no" ];then
#   restorefunc
   exit
  fi
  PKGSRC="."
  ;;
 99)
  echo
  ;;
 *)
#  restorefunc
  exit
  ;;
 esac
  
# gxmessage -borderless -font "DejaVu Sans 14" -center -bg "orange" -title "PETget" -buttons "" "Processing, please wait...
#Note: If wget has connected to the remote site then become \"stuck\",
#      just wait, as wget will keep retrying until download is successful." &
# MSGPID=$!
 echo "$PKGS2ADD" | sed -e 's/\\/\\\\/g' |
 while read HEAD1ST #WHILE-912
 do
  RETSTATUS=0
  APKGNAME="`echo "$HEAD1ST" | cut -f 2 -d '"'`" #' geany fix.
  QAPKGNAMEQ="^\"${APKGNAME}\""
  if [ ! "$PKGSRC" = "." ];then
   rm -f ./${APKGNAME}.tar.gz #precaution.
   rm -f ./${APKGNAME}.pet #precaution.
   #rxvt -name pet -bg orange -geometry 80x10 -e wget $PKGSRC/${APKGNAME}.pet
   
   yaf-splash -font "8x16" -outline 0 -margin 4 -bg orange -placement bottom -text "PETget package manager
Processing, please wait...
Note: If wget has connected to the remote site then become \"stuck\",
just wait, as wget will keep retrying until download is successful." & #9x15B also looks okay.
   MSGPID=$!
   if [ ! "`wget -t 2 -T 20 --waitretry=20 --spider -o /dev/stdout $PKGSRC/pet_packages-3/${APKGNAME}.pet | grep '200 OK'`" = "" ];then
    rxvt -name pet -bg orange -geometry 80x10 -e wget $PKGSRC/pet_packages-3/${APKGNAME}.pet
   else
    #fallback to downloading an old pupget package...
    if [ ! "`wget -t 2 -T 20 --waitretry=20 --spider -o /dev/stdout $PKGSRC/pupget_packages-1/${APKGNAME}.tar.gz`" = "" ];then
     rxvt -name pet -bg orange -geometry 80x10 -e wget $PKGSRC/pupget_packages-1/${APKGNAME}.tar.gz
    fi
   fi
   kill $MSGPID
  fi
  sync
  if [ -f ./${APKGNAME}.pet ];then
   pet2tgz ${WKGDIR}/${APKGNAME}.pet
   [ $? -ne 0 ] && RETSTATUS=1
  fi 
  if [ -f ./${APKGNAME}.tar.gz ];then
   if [ $RETSTATUS -eq 0 ];then
    #v2.13 test if enough space to expand tarball...
    #EXPFREEK=`df -k | grep ' /$' | tr -s ' ' | cut -f 4 -d ' '`
    EXPFREEB=`stat --filesystem --format=%f /` #no. free blocks.
    EXPFILEB=`stat --format=%b ${APKGNAME}.tar.gz` #no. blocks.
    EXPNEEDB=`expr $EXPFILEB \* 3` #.gz can expand about x2, need twice temp space.
    EXPSLACK=`expr $EXPFILEB \/ 10`
    EXPNEEDB=`expr $EXPNEEDB + $EXPSLACK`
    if [ $EXPNEEDB -gt $EXPFREEB ];then
     if [ ! "$DISABLEDX" = "yes" ];then
      gxmessage -center -name "pet" -bg "#ff8080" -title "PETget: エラー" " $APKGNAME パッケージはpackage has been downloaded to /root/.packages,
however there is not enough room to uncompress and install it.
The free space is $EXPFREEB blocks but it is estimated you will
need $EXPNEEDB blocks temporarily for the expansion and install.

Note: If you are using a pup_save.3fs personal storage file,
it can be made bigger -- see Utilities menu.

Click OK button to continue..."
     fi
     echo "ERROR: Not enough free space."
     rm -f ./${APKGNAME}.tar.gz
#     restorefunc #restore the previous database files.
     continue #next pet to install.
    fi
  
    if [ "`gzip --test --verbose ${APKGNAME}.tar.gz 2>&1 | grep "OK"`" = "" ];then
     RETSTATUS=1
    else
     #v2.13 '--absolute-names' needed for openoffice tarball to fix extraction error.
     tar --absolute-names -zxf ./$APKGNAME.tar.gz
     if [ $? -eq 0 ];then
      #v2.14 tgz2pet will embed a slackware-style binary tarball inside a directory
      #named APKGNAME, as the tarball expands direct to /...
      if [ -f $WKGDIR/$APKGNAME/${APKGNAME}.tar.gz ];then #tgz2pet also renames .tgz
       cd $WKGDIR/$APKGNAME/
       tar --absolute-names -zxf ./${APKGNAME}.tar.gz
       cd $WKGDIR
       sync
      fi
      #v2.14 pup2pet converts .pup to .pet by embedding inside tarball...
      if [ -f $WKGDIR/$APKGNAME/${APKGNAME}.pup ];then #pup2pet created this.
       installpupfunc
       #[ $? -ne 0 ] && RETSTATUS=1
       rm -rf $WKGDIR/$APKGNAME
       continue #install next pkg.
      fi
      APATTERN="s/.\/$APKGNAME//g"
      #a problem, if pkg has a symbolic link to an absolute path to a file, that is not yet
      #installed, it won't be included in the .files file...
      #so, instead of "-xtype f" will have two finds...
      #finds regular files only...
      find ./$APKGNAME -type f -mount -mindepth 2 | sed -e "$APATTERN" | sed -e 's/\/root0\//\/root\//g' > ./$APKGNAME.files
      sync
      #finds symbolic links only...
      find ./$APKGNAME -type l -mount -mindepth 2 | sed -e "$APATTERN" | sed -e 's/\/root0\//\/root\//g' >> ./$APKGNAME.files
      #this does actual install...
#      yaf-splash -font "8x16" -outline 0 -margin 4 -bg orange -text "PETget package manager
#Installing pkg, please wait..." & #9x15B also looks okay.
#      MSGPID=$!
      installpkgfunc #function call.
#      kill $MSGPID #killall xmessage
      #v2.14 turn it on...
      #escapes the '-' and '.' chars in pkg name...
      mAPKGNAME="`echo -n "$APKGNAME" | sed -e 's/\-/\\\-/g' | sed -e 's/\./\\\./g'`"
      #changes off to on...
      mPATTERN="s/\(^\"$mAPKGNAME\" \".*\"\) off \"/\1 on \"/g"
      cat ./livepackages.txt | sed -e "$mPATTERN" > /tmp/newlivepackages.txt
      sync
      mv -f /tmp/newlivepackages.txt ./livepackages.txt
     else
      RETSTATUS=1
     fi
    fi
   fi
  else
   RETSTATUS=1
  fi
  if [ $RETSTATUS -eq 1 ];then
    gxmessage -font "mono 14" -name "pet" -bg "#ff8080" -center -title "PETget" "失敗: $APKGNAME.pet のダウンロードは成功しませんでした"
    rm -f ./${APKGNAME}.tar.gz 2> /dev/null
    rm -f ./${APKGNAME}.pet 2> /dev/null
    #also need to turn "off" in livepackages.txt...
    ##well, could just delete the line, as it will get added back in from packages.txt next
    ##time run this script...
    #DPATTERN="\"$APKGNAME\""
    #cat $WKGDIR/livepackages.txt | grep -v "$DPATTERN" > /tmp/livepackages.txt
    #sync
    #rm -f $WKGDIR/livepackages.txt
    #mv /tmp/livepackages.txt $WKGDIR/livepackages.txt
#    restorefunc #restore the previous database files.
    rm ${WKGDIR}/${APKGNAME}.* 2> /dev/null
#  else
#   backupfunc #save the database files in /tmp.
  fi
 done #WHILE-912
 sync
 #kill $MSGPID
 if [ -s /tmp/missingpkgs.txt ];then
  #installpkgfunc() called dependcheckfunc() which write full details of missing dependencies to this file.
  PKGS2ADD="`cat /tmp/missingpkgs.txt`"
  #turn on entries in livepackages.txt...(even though not yet installed!)
  for ONE2ADD in `echo "$PKGS2ADD" | cut -f 2 -d '"' | tr  '\n' ' '`
  do
   MPATTERN="^\"${ONE2ADD}\" "
   cat $WKGDIR/livepackages.txt | grep "$MPATTERN" | grep '" off "' | sed -e 's/\" off \"/\" on \"/g' > /tmp/tempnewon
   if [ -s /tmp/tempnewon ];then
    cat $WKGDIR/livepackages.txt | grep -v "$MPATTERN" > /tmp/tempvvvv
    sync
    cat /tmp/tempnewon >> /tmp/tempvvvv
    sort /tmp/tempvvvv > $WKGDIR/livepackages.txt
    rm -f /tmp/tempvvvv
   fi
   rm -f /tmp/tempnewon
  done
  continue
 fi
 break
done #WHILE-PKGS2ADD


##END##
