#!/bin/bash

function die { echo "FATAL! $*"; exit 1; }

# ------------------------------------------------------------ main
pname=${0##*/}
echo "$pname, ver 1.00, (c) M. Liberi, jun 2022"

case $(uname) in
  AIX)		P=aix			;;
  HP-UX)	P=hp			;;
  CYGWIN*)	P=w32; exe=.exe
    case $(uname -m) in
      x86_64)	P=w64			;;
    esac				;;
  Linux)	P=lnx
    case $(uname -m) in
      x86_64)
        P=lnx64k2
	#k=$(uname -r)
	#k=${k%%.*}
        #case $k in
	#  [234])P=lnx64k$k		;;
	#  *)	die "unsupported Linux kernel $k"
	#esac
    esac				;;
  SunOS)	P=sun			;;
  Darwin)	P=mac			;;
  *)	die "unsupported platform"
esac

for p in wget gzip tar
do
  type $p >/dev/null 2>&1 ||die "can't find $p in PATH"
done

WD=/tmp/$pname.$$
mkdir -p $WD
cd $WD 	||die "can't cd into $WD"
trap "cd /tmp; rm -rf $WD" 0 1 2 3 15

source=http://mliberi.top/lx
target=/usr/ml
conf=/etc/$pname.conf

if test -r $conf
  then
    while read line
    do
      case $line in
	source=*)		source=${line#*=}	;;
	target=*)		target=${line#*=}	;;
      esac
    done <$conf
    echo "source repository is $source"
    echo "target dir is $target"
  else
    read -p "source repository [$source]: " x; test "$x" && source=$x
    read -p "target directory  [$target]: " x; test "$x" && target=$x
    {
      echo "source=$source"
      echo "target=$target"
    } >$conf
fi

x=offline_installer.bash
wget $source/$x	||die "can't wget $source/$x"
wget $source/$P.tgz
wget $source/any.tgz
export P target
if test -d "$target"
  then	# update
    $target/rxc -m1 -H -q >/dev/null 2>&1 ||{ # check if rxs is enabled
      read -p "enable rxx service (y/N)? " y
      test "$y" = y && args+=" rxs"
    }
    $target/tmout -t 1 $target/lra -H -S -q >/dev/null 2>&1 ||{	# check lrm
      read -p "enable lrm service (y/N)? " y
      test "$y" = y && args+=" lrm"
    }
#    $target/tmout -t 1 $target/sltn 127.0.0.1 59 </dev/null >/dev/null 2>&1	||{ #check cofs
#      read -p "enable cofs service (y/N)? " y
#      test "$y" = y && args+=" cofs"
#    }
  else	# install
    for s in rxs lrm # cofs
    do
      read -p "enable $s service (y/N)? " y
      test "$y" = y && args+=" $s"
    done
fi

bash $x $args

IFS=:
let ok=0
for p in $PATH
do
  test "$p" = "$target" && let ok=1 && break
done
((ok)) ||echo "consider adding $target to PATH"
