#!/usr/bin/ksh

######################################################################
# Name    : mkmiglst.ksh
# Function: Generate listfile to migrate a CMVC family to TeamConnection.
#           This generated file is the input to the migcmvc utility.
#
# NOTES: stdout prints take the form: print "<<STATUS>> ..."
#        stderr prints take the form: print -u2 "<<ERROR>> ..."
# Author  : Clifford J. Meyers
#######################################################################

#######################################################################
function usage
{
   print -u2 "\n\
mkmiglst.ksh:\n\
Purpose: Create a CMVC to TeamConnection migration listfile"
   print -u2 "Usage: ${PROG} [-h] [-f|-c] [-o <outfile>] [-r <release>] ..."
   RC=1
}

########################################################################
function help
{
   print -u2 "Description:"
   print -u2 "\
Generates a migration listfile to copy releases from CMVC to TeamConnection;\n\
this migration listfile is input to the migcmvc migration tool.\n\
This listfile contains the steps necessary to migrate all data related to\n\
specified releases.  This listfile contains comments to assist the user\n\
to manually customize the listfile for the migration process."
   print -u2 "\
Instructions are displayed for using listfile with migcmvc; the instructions \n\
are also saved in a file, myfile.instructions (by default)  \n\
If -o OutFile is used, the instructions are saved to OutFile.instructions."
   print -u2 "\
Options:-o: Specify filename for migration listfile.  Default=myfile.lst.\n\
        -f: Default. Migrate only FileView (snapshot of committed release).\n\
        -c: Migrate ChangeView (complete history of release).\n\
        -r ReleaseName: The release to be migrated.  Use -r for each release.\n\
            If no releases are specified then the user is prompted for them."
   print -u2 "\
Sample: # Listfile is myfile.lst, migrate FileView for two releases\n\
        mkmiglst.ksh -o myfile.lst -r v203 -r v204\n"
   RC=1
}

########################################################################
function initialize
{
        # program return code
        RC=0
        UID=$(id -u)
        GID=$(id -g)
        HOSTNAME=$(hostname -s)
        PROG=$(basename ${0})
        DIR=$(dirname ${0})
        MIGMODE=""
}

#######################################################################
# Generate output script
function process
{
        # output file for stdout
        if [[ $OUTFILE = "" ]]
        then
                OUTFILE="$$.lst"
        fi

        # remove files before writing
        if [[ -f $OUTFILE ]]
        then
                rm -if ${OUTFILE}
        fi
        if [[ -f ${OUTFILE}.instructions ]]
        then
                rm -if ${OUTFILE}.instructions
        fi

        # Formatting releases in set notation
        RELEASES=$(print "(${RELEASES}" | sed "s/,$/\)/")

        # remove output files
        cat >${OUTFILE} <<EOF
# If you use release.delete.ksh set maxerrors to 0
set maxerrors 100
# You can increase decache to increase performance if you do not approach
# your paging space limit during tests
set decache 1
# This is the recommended batchsize
set batchsize 1000
# Migrating individual tables
migrate Users
migrate HostView
migrate Authority
migrate Interest
migrate Cfgcomproc
migrate Cfgrelproc
migrate Config
migrate CompView
migrate bCompView where name = 'root'
migrate ReleaseView where name in (select releaseName from DefectView)
migrate EnvView
migrate AccessView
migrate NotifyView
migrate DefectView where state in ('open','returned','working') OR name in (select defectName from TrackView where releaseName in ${RELEASES} AND defectType = 'defect')
migrate FeatureView where state in ('open','returned','working') OR name in (select defectName from TrackView where releaseName in ${RELEASES} AND defectType = 'feature')
migrate TrackView where state in ('commit','complete') AND releaseName in ${RELEASES}
migrate FixView where releaseName in ${RELEASES} AND state = 'complete'
migrate ApproverView
migrate ApprovalView where releaseName in ${RELEASES}
migrate LevelView where releaseName in ${RELEASES} order by commitDate
migrate LevelMemberView where releaseName in ${RELEASES}
EOF
        exec 3>> $OUTFILE
        for release in ${RELEASELIST}
        do
          print -u3 "set top ${HOME}/extract/${release}"
          print -u3 "! mkdir -p ${HOME}/extract/${release}"
          print -u3 "! Release -extract ${release} -committed -node ${HOSTNAME} -root ${HOME}/extract/${release} -uid ${UID} -gid ${GID}"
          if [[ $MIGMODE = "f" ]]
          then
            print -u3 "# We recommend commenting out the FileView \
command "
            print -u3 "# and running it separately, after the database \
has been backed up."
            print -u3 "migrate FileView where versionSID = \
nuVersionSID AND releaseName = '${release}' AND dropDate is null"
          else
            print -u3 "# We recommend commenting out the FileView \
and ChangeView commands "
            print -u3 "# and running them separately, after the database \
has been backed up."
            print -u3 "migrate FileView where versionSID = \
nuVersionSID AND releaseName = '${release}' AND dropDate is null"
            print -u3 "migrate ChangeView where versionSID = \
nuVersionSID AND releaseName = '${release}' AND dropDate is null"
          fi
        done
cat >>${OUTFILE} <<EOF
migrate SizeView where releaseName in ${RELEASES}
migrate TestView where releaseName in ${RELEASES}
migrate VerifyView where defectName in (select name from DefectView where state in ('returned','working')) OR defectName in (select name from FeatureView where state in ('returned','working')) OR defectName in (select defectName from TrackView where releaseName in ${RELEASES})
migrate NoteView
migrate CoreqView
quit
EOF
}

#######################################################################
function cleanup
{
tee ${OUTFILE}.instructions <<EOF | more
PRE-MIGRATION RECOMMENDATIONS
-----------------------------
1.  Create a superuser login and a host list entry for the 
    TeamConnection family account in the CMVC family to be migrated.
2.  Backup the CMVC family and database.
3.  Cleanup and commit the work in progress in the target release(s) 
    using the following shell scripts.
      reassign.work.ksh
      release.complete.ksh
      release.delete.ksh
4.  The TeamConnection account needs to have the following environment 
    variables set:
      CMVC_FAMILY=<source family>
      TC_FAMILY=<target family>
      PATH=PATH:<location of CMVC executables>
    Note that the NLSPATH variable needs to have both the CMVC and the
    TeamConnection paths for the message catalog.
5.  Create an extract directory in the TeamConnection family $HOME
    directory that is NFS mountable from the CMVC server:
      \${FAMILYHOME}/extract
6.  Copy CMVC \${FAMILYHOME}/bin contents to the TeamConnection 
    directory \${FAMILYHOME}/bin.
7.  Copy CMVC \${FAMILYHOME}/config/userExits file to the TeamConnection
    file      \${FAMILYHOME}/config/userExit.
8.  Copy CMVC \${FAMILYHOME}/configField/DefectConfigTbl to TeamConnection
    file      \${FAMILYHOME}/cfgField/Defect.tbl
9.  Copy CMVC \${FAMILYHOME}/configField/FeatureConfigTbl to TeamConnection
    file      \${FAMILYHOME}/cfgField/Feature.tbl
10. You have to update the format files for the configurable fields in 
    order to put the appropriate sequence number for each field.

MIGRATION STEPS
---------------
1.  print "${OUTFILE}" | migcmvc migcmvc.out 2>&1 | at now
2.  For status: tail migcmvc.out
3.  To reference this instructions, see the file: ${OUTFILE}.instructions 


POST-MIGRATION RECOMMENDATIONS
------------------------------

1.  Create CMVC userExits and approval records to block any further
    work on the CMVC release.
2.  Execute the following TeamConnection commands to recreate the
    *.ld files:
      teamc Report -view authority -raw > authorit.ld
      teamc Report -view cfgcomp   -raw > comproc.ld
      teamc Report -view cfgrel    -raw > relproc.ld
      teamc Report -view interest  -raw > interest.ld
      teamc Report -view config -raw | awk -F\| '{ print "\$1|\$2|\$3|\$4|\$5|\"\$6\"" }' > config.ld
 
end of instructions
EOF
}

########################################################################
# main
initialize
while getopts :hfco:r: arg
  do
        case ${arg} in
          h)    usage
                help
                exit 1
                ;;
          f)    if [[ $MIGMODE = "" ]]
                then
                   MIGMODE=f
                else
                   print -u2 "Error: -f (FileView) and -c (ChangeView) may\
only be specified once."
                   RC=1
                fi
                ;;
          c)    if [[ $MIGMODE = "" ]]
                then
                   MIGMODE=c
                else
                   print -u2 "Error: -f (FileView) and -c (ChangeView) may\
only be specified once."
                   RC=1
                fi
                ;;
          r)    RELEASES="${RELEASES}'${OPTARG}',"
                RELEASELIST="${RELEASELIST} ${OPTARG}"
                ;;
          o)    if [[ $OUTFILE = "" ]]
                then
                   OUTFILE="${OPTARG}"
                else
                   print -u2 "Error: -o allows only 1 output filename"
                   RC=1
                fi
                ;;
          ?)    RC=1
                ;;
        esac
  done

# Set migration mode
MIGMODE=${MIGMODE:-f}
# Get releases if none specified on command line
if (( $RC == 0 )) && [[ $RELEASES = "" ]]
then
        NEWREL=""
        print -n "Release to be migrated (Just press Enter when done): "
        read -r NEWREL
        while [[ $NEWREL != "" ]]
        do
                if (($(echo $NEWREL | grep ' ' | wc -c) > 0))
                then
                   print -u2 "Error: Enter only 1 release with no spaces"
                else
                   RELEASES="${RELEASES}'${NEWREL}',"
                   RELEASELIST="${RELEASELIST} ${NEWREL}"
                fi

                print -n "Next release (Press Enter when done): "
                read -r NEWREL
        done
fi

# If no errors, generate output file
if (( ${RC} == 0 )) && [[ "${RELEASES}" != "" ]]
  then  process
        cleanup
  else  usage
fi
exit ${RC}

# end of file
