#! /bin/ksh
#
# Top level PI script for the SCO Open Source packages for Open Server.
# This script is the last in a long line of events that go to making
# installable images. Please see the file README, one level up from this
# file, for usage details.

# First, the list of products we recognise.
PRODUCTS="xorg gwxlibs perl apache extshells openssh vim"
DO_PAX=1

osrel=`uname -v`
case "$osrel" in
  6*) CPIO=/osr5/bin/cpio ;;
  *)  CPIO=/bin/cpio ;;
esac

function error {
  echo "ERROR: $@"
  exit 1
}

function warning {
  echo "WARNING: $@"
}

function validprd {
  case "$PRODUCTS" in
    *\ $1\ * | $1\ * | *\ $1) return 0 ;;
    *) return 1 ;;
  esac
}

function osr5prods {
  case "$OSR5_PRODUCTS" in
    $1 | *\ $1\ * | $1\ * | *\ $1) return 0 ;;
    *) return 1 ;;
  esac
}

function osr6prods {
  case "$OSR6_PRODUCTS" in
    $1 | *\ $1\ * | $1\ * | *\ $1) return 0 ;;
    *) return 1 ;;
  esac
}

function uw7prods {
  case "$UW7_PRODUCTS" in
    $1 | *\ $1\ * | $1\ * | *\ $1) return 0 ;;
    *) return 1 ;;
  esac
}

#
# Make a list of products, given the archive files found. The first arg
# is the variable to set, the rest is the list of archive files
function mkarchlist {
  typeset var
  typeset res
  typeset a

  var=$1; shift
  res=
  for a in $*; do
    f=${a##*/}
    p=${f%.cpio}
    [ "$p" = "$f" -o "$f" = "CVS" ] && continue
    validprd $p || {
      warning "Ignoring unknown $var product archive $f"
      continue
    }
    res="$res $p"
  done

  eval "${var}_PRODUCTS='$res'"
}

#
# Helper function to set a list of variables based on the products we
# support. The first argument is the variable suffix, the second the
# variable value, the third the OS to set it for all 'all' for all of
# them.
#
function setprdvars {
  typeset p
  typeset o
  typeset save_IFS
  typeset oslist

  oslist="osr5 osr6 uw7"

  [ -n "$3" ] && {
    [ "$3" = "all" ] || oslist=$3
  }

  save_IFS="$IFS"
  IFS=' '
  for p in $PRODUCTS; do
    for o in $oslist; do
      eval "${o}_${p}_$1='$2'"
    done
  done
  IFS="$save_IFS"
}

# Like the above but its first argument is the OS to set the variable for
function setosprdvars {
  typeset p

  for p in $PRODUCTS; do
    eval "${1}_${p}_$2='$3'"
  done
}

#
# Handle the -pi argument
#
function do_pi_arg {
  typeset arg
  typeset v
  typeset o
  typeset save_IFS
  typeset os
  typeset val

  # If the argument was specified at all, we have to reset to 0 all of the
  # pi variables as this list will contain all that we can process.
  setprdvars pi 0 all

  save_IFS="$IFS"
  IFS=','
  for arg in $1; do
    case $arg in
      -*) val=0
          arg=${arg#*-}
	  ;;
      *)  val=1 ;;
    esac

    case $arg in
      *:*) os=${arg#*:}
           arg=${arg%:*}
	   ;;
      *)   os=all
	   ;;
    esac

    if [ "$arg" = "all" ]; then
      setprdvars pi $val $os
    else
      validprd $arg || error "Invalid product $arg in argument -pi"
      [ "$os" = "all" ] && os="osr5,osr6,uw7"
      for o in $os; do
        eval "${o}_${arg}_pi=$val"
      done
    fi
  done
  IFS="$save_IFS"
}

#
# Handle the -osr5mp, -osr6mp and -uw7mp arguments
#
function do_mp_arg {
  typeset arg
  typeset v
  typeset prd
  typeset mp
  typeset os
  typeset save_IFS

  os=$1

  # Note that we don't reset the variables from their default

  save_IFS="$IFS"
  IFS=','
  for arg in $2; do
    prd=${arg%:*}
    mp=${arg#*:}
    case $mp in
      0 | [1-9] | [1-9][0-9] | [1-9][1-9][0-9]) ;;
      *) error "Invalid MP '$mp' for product '$prd' in argument -${os}mp" ;;
    esac
    if [ "$prd" = "all" ]; then
      setosprdvars $os mp $mp
    else
      validprd $prd || error "Invalid product '$prd' in argument -${os}mp"
      eval "${os}_${prd}_mp=$mp"
    fi
  done
  IFS="$save_IFS"
}

#
# Handle the -needosr5mp, -needosr6mp and -needuw7mp arguments
#
function do_needmp_arg {
  typeset arg
  typeset v
  typeset prd
  typeset mp
  typeset os
  typeset save_IFS

  os=$1

  # Note that we don't reset the variables from their default

  save_IFS="$IFS"
  IFS=','
  for arg in $2; do
    prd=${arg%:*}
    mp=${arg#*:}
    case $mp in
      0 | [1-9] | [1-9][0-9] | [1-9][0-9][0-9]) ;;
      *) error "Invalid MP '$mp' for product '$prd' in argument -need${os}mp" ;;
    esac
    if [ "$prd" = "all" ]; then
      setosprdvars $os needmp $mp
    else
      validprd $prd || error "Invalid product '$prd' in argument -need${os}mp"
      eval "${os}_${prd}_needmp=$mp"
    fi
  done
  IFS="$save_IFS"
}

#
# Handle the -type argument
#
function do_type_arg {
  typeset arg
  typeset save_IFS

  # If this arg was specified at all we have to reset the defaults to 0
  DO_bundled=0
  DO_standalone=0

  save_IFS="$IFS"
  IFS=','
  for arg in $1; do
    case "$arg" in
      bundled) DO_bundled=1 ;;
      standalone) DO_standalone=1 ;;
      both) DO_bundled=1; DO_standalone=1 ;;
      *) error "Invalid productization type '$arg' in -type argument" ;;
    esac
  done
  IFS="$save_IFS"
}

#
# Handle the -os argument
#
function do_os_arg {
  typeset arg
  typeset save_IFS

  # If the arg was passed at all we reset all OSes to 0 (off)
  DO_osr5=0
  DO_osr6=0
  DO_uw7=0

  save_IFS="$IFS"
  IFS=','
  for arg in $1; do
    case "$arg" in
      osr5) DO_osr5=1 ;;
      osr6) DO_osr6=1 ;;
      uw7) DO_uw7=1 ;;
      all) DO_osr5=1; DO_osr6=1; DO_uw7=1 ;;
      *) error "Invalid OS type '$arg' in -os argument" ;;
    esac
  done
  IFS="$save_IFS"
}

#
# Check to make sure that the archives for the given OS exist.
#
function check_for_archives {
  typeset p

  [ "$DO_osr5" = "1" ] && {
    for p in $PRODUCTS; do
      eval doprd=\$osr5_${p}_pi
      [ "$doprd" = "1" ] && {
	osr5prods $p || {
	  got_archives=0
	  echo "ERROR: Requested productization of OSR5 $p but the archive is missing"
        }
      }
    done
  }

  [ "$DO_osr6" = "1" ] && {
    for p in $PRODUCTS; do
      eval doprd=\$osr6_${p}_pi
      [ "$doprd" = "1" ] && {
	osr6prods $p || {
          uw7prods $p || {
	    got_archives=0
	    echo "ERROR: Requested productization of OSR6 $p but the archive is missing"
	  }
        }
      }
    done

    #
    # We have a special case for OSR6, because of its dual ABI world. If
    # we've been asked to productize GWXLIBS or XORG, we need both the
    # OSR5 and UW7 versions available.
    #
    [ "$osr6_gwxlibs_pi" = "1" ] && {
      osr5prods gwxlibs || {
	got_archives=0
	echo "ERROR: Requested productization of OSR6 gwxlibs but the OSR5 gwxlibs is missing"
      }
      uw7prods gwxlibs || {
	got_archives=0
	echo "ERROR: Requested productization of OSR6 gwxlibs but the UW7 gwxlibs is missing"
      }
    }
  }

  [ "$DO_uw7" = "1" ] && {
    for p in $PRODUCTS; do
      eval doprd=\$uw7_${p}_pi
      [ "$doprd" = "1" ] && {
	uw7prods $p || {
	  got_archives=0
	  echo "ERROR: Requested productization of UW7 $p but the archive is missing"
        }
      }
    done
  }
}

###
### Main script logic starts here
###

[ "$*" = "list" ] && {
  echo "Valid products: $PRODUCTS"
  exit 0
}

topdir=`pwd`

# Now the type of packages we will be producing. Defaults to both.
DO_bundled=1
DO_standalone=1

# By default we productize for all 3 OSes
DO_osr5=1
DO_osr6=1
DO_uw7=1

# Set the default MP for each product to "let the control script set it"
setprdvars mp x all
# Set the default needed MP for each product to "let the control script set it"
setprdvars needmp x all
# Set the default for packing the product to "yes"
setprdvars pi 1 all

# Check the startup requirements
[ -x ./metapkg ] || error "missing MetaPKG binary"
[ -x ./pax ] || error "missing AST pax binary"
[ -d data ] || error "missing data directory"
[ -d dist ] || error "missing dist directory"
[ -d dist/osr5 -o -d dist/uw7 ] || error "invalid dist directory"

found_osr5=`echo dist/osr5/*`
found_osr6=`echo dist/osr6/*`
found_uw7=`echo dist/uw7/*`

[ "$found_osr5" = "dist/osr5/*" -a "$found_uw7" = "dist/uw7/*" ] && {
  error "no archives in dist/osr5 or dist/uw7"
}

# Set the actual packages found for each of the two distribution trees
[ "$found_osr5" = "dist/osr5/*" ] || mkarchlist OSR5 $found_osr5
[ "$found_osr6" = "dist/osr6/*" ] || mkarchlist OSR6 $found_osr6
[ "$found_uw7" = "dist/uw7/*" ] || mkarchlist UW7 $found_uw7

[ -z "$OSR5_PRODUCTS" -a -z "$UW7_PRODUCTS" -a -z "$OSR6_PRODUCTS" ] && {
  error "No valid product archives to process"
}

#
# Now process the command line arguments
#
while [ $# -ne 0 ]; do
  arg=${1%=*}
  val=${1#*=}
  shift
  case $arg in
    -pi) do_pi_arg $val ;;
    -os) do_os_arg $val ;;
    -osr5mp) do_mp_arg osr5 $val ;;
    -osr6mp) do_mp_arg osr6 $val ;;
    -uw7mp) do_mp_arg uw7 $val ;;
    -needosr5mp) do_needmp_arg osr5 $val ;;
    -needosr6mp) do_needmp_arg osr6 $val ;;
    -needuw7mp) do_needmp_arg uw7 $val ;;
    -type) do_type_arg $val ;;
    -nopax) DO_PAX=0 ;;
    *) error "Unknown option: $arg" ;;
  esac
done

# Make sure we have all the archives we need
got_archives=1
check_for_archives
[ "$got_archives" = "1" ] || error "Missing archives. Cannot continue."

[ "$DO_PAX" = "1" ] && {
  # We're ready to start. Clean out the directories first
  [ -d output ] && {
    echo "Removing old output directory"
    rm -fr output
  }

  [ -d logs ] && {
    echo "Removing old logs directory"
    rm -fr logs
  }

  mkdir output logs

  [ "$DO_osr5" = "1" ] && {
    mkdir output/osr5
    [ "$DO_bundled" = "1" ] && mkdir output/osr5/bundled
    [ "$DO_standalone" = "1" ] && {
      mkdir output/osr5/standalone
      mkdir output/osr5/archives
    }
  }

  [ "$DO_osr6" = "1" ] && {
    mkdir output/osr6
    [ "$DO_bundled" = "1" ] && mkdir output/osr6/bundled
    [ "$DO_standalone" = "1" ] && {
      mkdir output/osr6/standalone
      mkdir output/osr6/archives
    }
  }

  [ "$DO_uw7" = "1" ] && {
    mkdir output/uw7
    [ "$DO_bundled" = "1" ] && mkdir output/uw7/bundled
    [ "$DO_standalone" = "1" ] && {
      mkdir output/uw7/standalone
      mkdir output/uw7/archives
    }
  }

  [ -d tmp ] && {
    echo "Removing old tmp directory"
    mv tmp remove_tmp
    rm -fr remove_tmp > /dev/null 2>&1
  }

  [ -d remove_tmp ] && {
    cat <<EOF
WARNING: Due to a bug in HTFS, the remove_tmp directory could not be
         completely removed. The only way to effectively clean up is
	 to unmount the filesystem and run fsck -o full on it. This
	 can take a long time if you have a very large filesystem.
	 For this reason it is highly recommended that you do the PI
	 runs of these open source packages on a small filesystem, or
	 do the PI on OSR6, whose VxFS filesystem is not affected by
	 this bug.
EOF
  }

  #
  # Unwind all the archives into the tmp directories
  #
  mkdir tmp
  for os in osr5 osr6 uw7; do
    eval doit=\$DO_${os}
    [ "$doit" = "1" ] && {
      mkdir $topdir/tmp/$os

      for p in $PRODUCTS; do
        arcos=$os
        [ "$os" = "osr5" ] || arcos=uw7
	[ "$os" = "osr6" ] && {
	  [ -f $topdir/dist/$os/${p}.cpio ] && arcos=osr6
	}
        eval dp=\$${os}_${p}_pi
        [ "$dp" = "1" ] && {
  	  cd $topdir/tmp/$os
  	  mkdir $p
  	  cd $p
  	  mkdir input
  	  if [ "$os" = "osr6" -a "$p" = "gwxlibs" ]; then
  	    echo "Extracting UW7 ${p} for ${os}"
  	    $topdir/pax -r -f $topdir/dist/uw7/${p}.cpio \
	      -s ',^gwxlibs$,dist,' \
	      -s ',^gwxlibs/,dist/,' || {
  	      error "extraction of UW7 $p for $os failed"
  	    }

  	    echo "Extracting OSR5 ${p} for ${os}"
  	    $topdir/pax -r -f $topdir/dist/osr5/${p}.cpio \
	      -s ',^gwxlibs$,dist,' \
	      -s ',^gwxlibs/,dist/,' \
	      -s ',^dist/[^/]*,&/osr5,' || {
  	      error "extraction of OSR5 $p for $os failed"
  	    }
  	  else
  	    echo "Extracting ${os} ${p}"
  	    $topdir/pax -r -f $topdir/dist/$arcos/${p}.cpio \
	      -s ",^${p}\$,dist," \
	      -s ",^${p}/,dist/," || {
  	      error "extraction of $tp $p for $os failed"
  	    }
  	  fi
        }
      done # Loop through products
    }
  done # Loop through OS type
}

#
# Now that all of the archives have been unwound, we can proceed with the
# MetaPKG runs for each OS and product type we will be doing.
#
dstamp=`date +%Y%m%d`
for os in osr5 osr6 uw7; do
  # We need an upper-case OS name for MetaPKG
  OS=$os
  typeset -u OS	

  eval doit=\$DO_${os}
  [ "$doit" = "1" ] && {
    for p in $PRODUCTS; do
      P=$p
      typeset -u P

      # OpenSSH isnt supported on UnixWare
      [ "$os" = "uw7" -a "$p" = "openssh" ] && continue

      eval dp=\$${os}_${p}_pi
      [ "$dp" = "1" ] && {
	for tp in bundled standalone; do
	  # GNU Tools doesnt support bundled builds because it is always a
	  # standalone installation only.
	  [ "$tp" = "bundled" -a "$p" = "gnutools" ] && continue
	  eval dtp=\$DO_${tp}
	  logfile=$topdir/logs/${os}-${tp}-${p}.log
	  [ "$dtp" = "1" ] && {
	    cd $topdir/tmp/$os/$p

            # Build up the arguments we will be passing to MetaPKG
	    MPSARG=
	    MPMPARG=
	    MPOSARG="-MDESTOS=$OS"

	    if [ "$tp" = "standalone" ]; then
	      MPSARG="-MSTANDALONE=1"
              # If its not bundled then we need to tell the control script
	      # which MP this is in. If the value is x, it means we don't
	      # have a specific MP passed on the command line and we should
	      # use the default in the control script. If that specific
	      # number is 0, it means this does not appear in an MP.
	      #
	      # Also, if we are ONLY producing a standalone archive then
	      # we need to let the control scripts know that, so that they
	      # can do both phases of the prep work in one shot.
	      [ "$DO_bundled" = "0" ] && {
		MPSARG="$MPSARG -MNO_BUNDLED=1"
	      }
	      eval tmp=\$${os}_${p}_mp
	      MPMPARG="-DDESTMP=$tmp"
	      eval tmp=\$${os}_${p}_needmp
	      MPMPARG="$MPMPARG -DNEEDMP=$tmp"
	    fi

	    # Invoke MetaPKG and log the results
	    echo "Invoking MetaPKG for $os $tp $p ..."
	    echo "$topdir/metapkg -p $topdir/data/metapkg.${p} -d $topdir/tmp/$os/$p $MPMPARG $MPSARG $MPOSARG -MHANDOFFS=$topdir/data" > $logfile
	    $topdir/metapkg -p $topdir/data/metapkg.${p} -d $topdir/tmp/$os/$p $MPMPARG $MPSARG $MPOSARG -MHANDOFFS=$topdir/data >> $logfile 2>&1 || {
	      error "MetaPKG invocation for ${os} ${tp} ${p} failed"
	    }

	    # If this was a standalone we have two archives to create. The
	    # first is the archive with the volumes, then we do a make clean
	    # and save the archive of the packaging tree itself.
	    if [ "$tp" = "standalone" ] ; then
	      [ "$os" = "uw7" ] || {
		mv CDMT.MACROS cdmt.config
	      }
	      echo "Making installable archives for ${os} ${p}"
	      make >> $logfile 2>&1
	      if [ "$os" = "uw7" ]; then
		mv -f ${P}.pkg $topdir/output/${os}/archives/${P}-${dstamp}.pkg
	      else
		cd archives
		mv TAPE ${p}
	        echo "Creating VOL archive for ${os} ${p}"
		find ${p} -depth -print | $CPIO -oc -O $topdir/output/${os}/archives/${p}-${dstamp}.cpio
		cd ..
	      fi
	      make clean > /dev/null 2>&1
	      cd ..
              echo "Creating PI archive for ${tp} ${os} ${p}"
	      find ${p} -depth -print | $CPIO -oc -O $topdir/output/${os}/standalone/${p}-${dstamp}.cpio
	    else
	      [ "$os" = "uw7" ] || {
		mv CDMT.MACROS cdmt.config
	      }
	      cd ..
              echo "Creating PI archive for ${tp} ${os} ${p}"
	      find ${p} -depth -print | $CPIO -oc -O $topdir/output/${os}/bundled/${p}-${dstamp}.cpio
	    fi
	  }
	done # Loop through bundled / standalone
      }
    done # Loop through products
  }
done # Loop through OS type
