#! /bin/tclsh

# a script to pull all the bits and such together to build a
# rpm file for filerunner.

# For input we need (these may be defined by env or command line):
#
# EMAIL=<email address of builder>
# NAME=<name of builder>
# TAR=<TAR or TARgz of the source files>
#
# In addition the command line parms are:
# -v     set verbose mode
# -h     help
# -nodeb do not build the .deb package
#
#
# We will deduce the version from the TAR file name.

# This code uses the following file directory structures:
# ~/rpmbuild/ where we do all the work...
# ~/rpmbuild/BUILD
# ~/rpmbuild BUILDROOT
# ~/rpmbuild/RPMS
# ~/rpmbuild/SOURCES
# ~/rpmbuild/SPECS
# ~/rpmbuild/SRPMS
#
# If any of these don't exist, they are created.

if {$tcl_platform(platform) eq "windows"} {
  puts "At this time we do not support building RPMs in MSW"
  exit 1
}

set dirs [list BUILD BUILDROOT RPMS SOURCES SPECS SRPMS]
set legal [list EMAIL NAME TAR]
set legalmin {v nodeb h help}

foreach parm $legalmin {
  set $parm 0
}
set wd [pwd]
#
# Default name to current users name
#
set nam [exec getent passwd $env(USER)]
set NAME [lindex [split $nam ":"] 4]

proc echo {mess} {
  if {$::v} {puts $mess}
}

foreach parm $legal {
  if {[info exists env($parm)]} {
    set $parm $env($parm)
  }
}

set changelist {}

foreach ent $argv {
  echo $ent
  lassign [split $ent "-" ] arg val ext
  if {$arg == {} } {
    # The following allows '--' instead of just '-'
    if {$val == {} } {set val $ext}
    if {$val ni $legalmin } {
      puts "Bad argument \"$ent\". Must be one of $legalmin."
      exit
    }
    set $val 1
    lappend changelist $val
    switch $val {
      help {set h 1}
    }
    continue
  }
  lassign [split $ent "="] arg val
  echo "$arg $val"
  if {$arg ni $legal} {
    puts "Bad argument \"$ent\". Must be one of $legal=path"
    exit 1
  }
  set $arg $val
  lappend changelist $arg
}
if {$h } {
  puts "
     This is the RPM build script.  While written for filerunner an
     attempt has been made to make a general script to build RPM
     binary and source packages.  The following parameters may be
     entered on the command line or env variables:

     EMAIL=<email address of builder>
     NAME=<name of builder> Defaultes to users full name from password file
     TAR=<TAR or TARgz of the source files>

     In addition the following command line parameters are recognized:

     -v     set verbose mode
     -nodeb do not produce the .deb package
     -h     produce this message
     -help  produce this message
 
     The script derives the version from the TAR file name which is assumed
     to be of the form <name>-<version>.tar\[.gz]. 

     The script expects the spec file to be in the TAR. 

     This script builds and works in the following directories:

     ~/rpmbuild/BUILD
     ~/rpmbuild BUILDROOT
     ~/rpmbuild/RPMS
     ~/rpmbuild/SOURCES
     ~/rpmbuild/SPECS
     ~/rpmbuild/SRPMS    any existing content here is deleted

     This script passes three macros to rpmbuild:
     _version    which is set to the version, and
     _timeuser   which is \"* date NAME EMAIL version\" and
     _verb       which is either \"-verbose\" or not defined
                 to be used as %{?_verb} (in filerunners case in INSTALL)
     _verb will be defined if \"-v\" is in the invocation.  This will
           also cause rpmbuild to be called with \"-vv\".

     _timeuser is ment to be used in the %changelog

     The result will be found in ~/rpmbuild/RPMS and ~/rpmbuild/SRPMS.
    "
exit 0
}

foreach ent $legal {
  if {![info exists $ent] || [set $ent] == {} } {
    puts "Must have $legal. Could not find $ent. Done!"
    exit 1
  }
}
set tar [file tail  $TAR ]

set mode "name"
for {set cr 0} {$cr < [string length $tar]} {incr cr}  {
  set ch [string range $tar $cr $cr]
  switch $mode {
    name {
      if {[string is alnum $ch]} {continue}
      if {$ch == "-" && [string is digit [string range $tar $cr+1 $cr+1]]} {
	set vStart $cr
	set Name [string range $tar 0 $cr-1]
	set mode "version"
      }
    }
    version {
      if {$ch == "." || [string is digit $ch]} {continue}
      set version [string range $tar $vStart+1 $cr-2]
      break
    }
  }	
}

foreach parm {Name version} {
  if {[info exists $parm]} {
    echo "Default $parm is [set $parm]"
  } else {
    echo "Could not find $parm while parsing $TAR"
    if {$parm == "version"} {
      puts "Failed to find version in the Tar name $TAR"
      puts "Quiting..."
      exit 1
    }
  }
}

foreach dir $dirs {
  file mkdir ~/rpmbuild/$dir
  set ${dir}dir [file normalize ~/rpmbuild/$dir]
}

# clean up the spec dir...
foreach fl [glob -nocomplain $SPECSdir/*] {
  file delete -force $fl
}

file copy -force $TAR ~/rpmbuild/SOURCES

# get the spec file from the archive... we only assume it is in there...
set tarfile [file normalize ~/rpmbuild/SOURCES/$tar]
cd $SPECSdir
set foo [catch "exec tar -xf $tarfile *.spec" out]
echo "$out"

# ok, now track down what we just did
while {[set spec [glob -nocomplain *]] != {} && \
	   [llength $spec] == 1 && \
	   [file isdirectory $spec] } { cd $spec}

if {[llength $spec] != 1 || [file extension $spec] != ".spec" } {
  puts "There appears to be more than one spec file: $spec"
  puts "dazed and confused, quiting"
  exit 1
}
file rename $spec  $SPECSdir/$spec
cd $SPECSdir

foreach fil [glob -nocomplain *] {
  if {[file isdirectory $fil]} {
    file delete -force $fil
  }
}

if {![file readable $SPECSdir/$spec]} {
  puts "Failed to find the spec file in $TAR"
  puts "Quiting..."
  exit 1
}
#
# Modify the spec file to put in the date, user name and email address
#
set date [clock format [clock seconds] -format {%a %b %d %Y}] 
set newline "* $date $NAME $EMAIL $version"

if {$v} {
  echo "exec rpmbuild -ba -vv\
              -D \"_version $version\" \
              -D \"_timeuser $newline\" \
              -D \"_verb -verbose\" $spec"
  set r [catch "exec rpmbuild -ba -vv\
             -D \"_version $version\"\
             -D \"_timeuser $newline\" \
             -D \"_verb -verbose\" $spec" out]
} else {
  set r [catch "exec rpmbuild -ba\
            -D \"_version $version\" \
            -D \"_timeuser $newline\" $spec" out]
}

puts "$out"
if {[llength [glob -nocomplain $RPMSdir/*]] == 0} {
  puts "Build appears to have failed!  Quitting."
  exit 1
}
if {$nodeb} {
  exit 0
}
cd $wd

set r [catch "exec ./alien.tcl [expr {$v ? {-v} : {}}]\
                             \"NAME=$NAME\" \
                             \"EMAIL=$EMAIL\" \
                             \"PACKAGE=[file rootname $spec]\" \
                             \"VERSION=$version\" " out]
puts "$out"
exit $r
