#!/bin/sh
#
######################################################
# Build script for piCore64-15.x                     #
#                                                    #
# See .info for details                              #
######################################################

######################################################
# Prepare extension creation                         #
######################################################
#download and install dependencies
tce-load -wi node.tcz
#download and install the compile tools
tce-load -wi bash.tcz
tce-load -wi curl.tcz
tce-load -wi go.tcz
tce-load -wi compiletc.tcz
tce-load -wi squashfs-tools.tcz

######################################################
# Configure extension creation parameters            #
######################################################
# Variables
TODAY=`date +%Y/%m/%d`
PACKAGE="prometheus"
VERSION="3.1.0"
DESCRIPTION="Prometheus is a systems and service monitoring system."
DOCDESCRIPTION="Documentation part of Prometheus"
DEVDESCRIPTION="Development files part of Prometheus"
AUTHORS="https://github.com/prometheus/prometheus/blob/main/MAINTAINERS.md"
HOMEPAGE="https://prometheus.io/"
LICENSE="Apache-2.0 license"
ME="rhermsen"
TAGS="prometheus"
DOCTAGS="man pages prometheus"
DEVTAGS="development prometheus"
DESTDIR=/mnt/mmcblk0p2/tce/dest/${PACKAGE}
TMPDIR=/mnt/mmcblk0p2/tce/submit/${PACKAGE}
SRCDIR=/mnt/mmcblk0p2/tce/${PACKAGE}
ARCH=`uname -m`

# Workdir
sudo rm -r ${SRCDIR}/${PACKAGE}-${VERSION} 2>/dev/null
[ ! -d ${SRCDIR} ] && mkdir ${SRCDIR}

# Source
cd ${SRCDIR}
[ ! -f   ${SRCDIR}/v${VERSION}.tar.gz ] && wget https://github.com/${PACKAGE}/${PACKAGE}/archive/refs/tags/v${VERSION}.tar.gz
tar xzf v${VERSION}.tar.gz

cd ${SRCDIR}/${PACKAGE}-${VERSION}


######################################################
# Compile extension                                  #
######################################################

# Export variables needed for compilation
ARCH=`uname -m`
if [ $ARCH == "armhf" ]
then
echo
export CFLAGS="-Os -pipe -march=armv6zk -mtune=arm1176jzf-s -mfpu=vfp"
export CXXFLAGS="-Os -pipe -march=armv6zk -mtune=arm1176jzf-s -mfpu=vfp"
elif [ $ARCH == "aarch64" ]
then
export CFLAGS="-Os -pipe -march=armv8-a+crc -mtune=cortex-a72"
export CXXFLAGS="-Os -pipe -march=armv8-a+crc -mtune=cortex-a72"
echo
else
exit 1
fi
export LDFLAGS="-Wl,-O1"
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:/usr/lib/pkgconfig

# Compile
cd /${SRCDIR}/${PACKAGE}-${VERSION}

# make
time make build

# Below lines just for savekeeping in case make is used in a build script, and needs troubleshooting.
# https://stackoverflow.com/questions/5820303/how-do-i-force-make-gcc-to-show-me-the-commands
# make -n install
# make SHELL='sh -x' DESTDIR=$DESTDIR install 

######################################################
# Base extension                                     #
######################################################
sudo rm -r ${TMPDIR}* 2>/dev/null

mkdir -p  ${TMPDIR}/usr/local/bin
mkdir -p  ${TMPDIR}/usr/local/etc/${PACKAGE}/default
mkdir -p  ${TMPDIR}/usr/local/share/doc/${PACKAGE}
mkdir -p ${TMPDIR}/usr/local/etc/init.d
mkdir -p ${TMPDIR}/usr/local/tce.installed

cp  /${SRCDIR}/${PACKAGE}-${VERSION}/prometheus ${TMPDIR}/usr/local/bin
cp  /${SRCDIR}/${PACKAGE}-${VERSION}/promtool ${TMPDIR}/usr/local/bin
cp  /${SRCDIR}/${PACKAGE}-${VERSION}/documentation/examples/prometheus.yml ${TMPDIR}/usr/local/etc/${PACKAGE}/prometheus_example.yml
cp ${SRCDIR}/${PACKAGE}-${VERSION}/LICENSE ${TMPDIR}/usr/local/share/doc/${PACKAGE}/
cp ${SRCDIR}/${PACKAGE}-${VERSION}/NOTICE ${TMPDIR}/usr/local/share/doc/${PACKAGE}/

###################################################
# Create info file                                #
###################################################
cd /mnt/mmcblk0p2/tce/submit/
if [ $ARCH == "armhf" ]
then
cat <<EOF> ${PACKAGE}.tcz.info
Title:          ${PACKAGE}.tcz
Description:    ${DESCRIPTION}
Version:        ${VERSION}
Author:         ${AUTHORS}
Original-site:  ${HOMEPAGE}
Copying-policy: ${LICENSE}
Size:           ${size}
Extension_by:   ${ME}
Tags:           ${TAGS}
Comments:       Prometheus, a Cloud Native Computing Foundation project,
                is a systems and service monitoring system. It collects metrics
                from configured targets at given intervals, evaluates rule expressions,
                displays the results, and can trigger alerts when specified conditions
                are observed.
                Start with:
                sudo /usr/local/etc/init.d/prometheus {start|stop|restart|force-reload|status}
                or
                sudo /usr/local/bin/prometheus --config.file=/usr/local/etc/prometheus/prometheus.yml \\
                 --storage.tsdb.path=/usr/local/etc/prometheus/data/

                The database can be saved to a location of choice by configuring the enviroment 
                variable DATA_DIR in /usr/local/etc/prometheus/default/prometheus.
                If not set the default '/usr/local/etc/prometheus/data/' will be used.
                Be aware that unsaved database content will be lost if not backupped
                ('filetool.sh -b') when stored in the default location.
Change-log:     ${TODAY} First version, ${VERSION} (${ME})
Current:        ${TODAY} First version, ${VERSION} (${ME})
EOF
elif [ $ARCH == "aarch64" ]
then
cat <<EOF> ${PACKAGE}.tcz.info
Title:          ${PACKAGE}.tcz
Description:    ${DESCRIPTION}
Version:        ${VERSION}
Author:         ${AUTHORS}
Original-site:  ${HOMEPAGE}
Copying-policy: ${LICENSE}
Size:           ${size}
Extension_by:   ${ME}
Tags:           ${TAGS}
Comments:       Prometheus, a Cloud Native Computing Foundation project,
                is a systems and service monitoring system. It collects metrics
                from configured targets at given intervals, evaluates rule expressions,
                displays the results, and can trigger alerts when specified conditions
                are observed.
                Start with:
                sudo /usr/local/etc/init.d/prometheus {start|stop|restart|force-reload|status}
                or
                sudo /usr/local/bin/prometheus --config.file=/usr/local/etc/prometheus/prometheus.yml \\
                 --storage.tsdb.path=/usr/local/etc/prometheus/data/

                The database can be saved to a location of choice by configuring the enviroment 
                variable DATA_DIR in /usr/local/etc/prometheus/default/prometheus.
                If not set the default '/usr/local/etc/prometheus/data/' will be used.
                Be aware that unsaved database content will be lost if not backupped
                ('filetool.sh -b') when stored in the default location.
Change-log:     ${TODAY} First version, ${VERSION} (${ME})
Current:        ${TODAY} First version, ${VERSION} (${ME})
EOF
fi

###################################################                                                              
# Create .dep file                                #                                                              
###################################################
cat <<EOF> /mnt/mmcblk0p2/tce/submit/${PACKAGE}.tcz.dep
bash.tcz
EOF

###################################################
# Create install script file                      #
###################################################
cat <<EOF> $TMPDIR/usr/local/tce.installed/${PACKAGE}
#!/bin/sh
if [ ! -f /usr/local/etc/${PACKAGE}/${PACKAGE}.yml ]; then
        cp /usr/local/etc/${PACKAGE}/${PACKAGE}_example.yml /usr/local/etc/${PACKAGE}/${PACKAGE}.yml
        echo "usr/local/etc/${PACKAGE}" >>  /opt/.filetool.lst
fi
chown -R tc:staff /usr/local/etc/${PACKAGE}
EOF








###################################################
# Create init.d script file                       #
###################################################
cat <<EOF> $TMPDIR/usr/local/etc/init.d/${PACKAGE}
#! /usr/bin/env bash

NAME=prometheus
DEFAULT=/usr/local/etc/prometheus/default/\$NAME

PROMETHEUS_USER=tc
PROMETHEUS_GROUP=staff
CONF_DIR=/usr/local/etc/prometheus
CONF_FILE=\${CONF_DIR}/prometheus.yml
# DATA_DIR=/usr/local/etc/prometheus/data/
# DATA_DIR=/mnt/mmcblk0p2/tce/prometheus/data/
DATA_DIR="\${DATA_DIR_ENV:-/usr/local/etc/prometheus/data/}"
PID_FILE=/var/run/\$NAME.pid
DAEMON=/usr/local/bin/prometheus

if [ ! -x \$DAEMON ]; then
  echo "Program not installed or not executable"
  exit 5
fi

# overwrite settings from default file
if [ -f "\$DEFAULT" ]; then
  . "\$DEFAULT"
fi

DAEMON_OPTS="--config.file=\${CONF_FILE} --storage.tsdb.path=\${DATA_DIR}"

function checkUser() {
  if [ \`id -u\` -ne 0 ]; then
    echo "You need root privileges to run this script"
    exit 4
  fi
}

case "\$1" in
  start)
    checkUser
    pid=\`pidof \$NAME\`
    if [ -n "\$pid" ] ; then
      echo " \${DAEMON} Already running."
      exit 0
    fi

    # Prepare environment
    [ ! -d \$DATA_DIR ] && mkdir -p "\$DATA_DIR"
    chown -R "\$PROMETHEUS_USER":"\$PROMETHEUS_GROUP" "\$DATA_DIR"
    [ ! -f "\$PID_FILE" ] && touch "\$PID_FILE"
    # should not change ownership of a pid file to a non-root user. This introduces a security risk.
    # chown "\$PROMETHEUS_USER":"\$PROMETHEUS_GROUP" "\$PID_FILE"

    # Start Daemon
    start-stop-daemon -S -n \${NAME} -x \${DAEMON} -p \${PID_FILE} -m -b -v -c "\$PROMETHEUS_USER":"\$PROMETHEUS_GROUP" -- \$DAEMON_OPTS
    sleep 1
    # check if pid file has been written to
    if ! [[ -s \$PID_FILE ]]; then
      echo "Failed to start \${DAEMON}"
      rm -f "\${PID_FILE}"
      exit 1
    else
      echo " \${DAEMON} started"
    fi
    ;;
  stop)
    checkUser
    echo "Stopping \${DAEMON} if running"

    if [ -f "\$PID_FILE" ]; then
      start-stop-daemon -K -n \${NAME} -x \${DAEMON} -p \${PID_FILE} -s TERM
      sleep 1
      pid=\`pidof \$NAME\`
      if [ -n "\$pid" ] ; then
        echo "Failed to stop \${DAEMON} (pid \$pid)"
      else
        rm -f "\${PID_FILE}"
      fi
    else
      pid=\`pidof \$NAME\`
      if [ -n "\$pid" ] ; then
        start-stop-daemon -K -n \${NAME} -x \${DAEMON} -s TERM
      else
        echo "\${DAEMON} is not running"
      fi
    fi
    echo "."
    ;;
  status)
    pid=\`pidof \$NAME\`
    PID=\`cat \$PID_FILE 2>/dev/null\` 
    if [[ -s \$PID_FILE ]]; then
        if [[ "\$pid" == "\$PID" ]]; then
          echo " \${DAEMON} is running. (pid \$pid)"
        else
          echo "\${DAEMON} is not running but a PID file exist (\$PID_FILE = \$PID)"
        fi
    else
      if [ ! -z "\$pid" ] ; then
        echo "\${DAEMON} is running but no PID file exist (PID = \$pid)"
      else
       echo "\${DAEMON} is not running"
      fi
    fi
    ;;
  restart|force-reload)
    if [ -f "\$PID_FILE" ]; then
      \$0 stop
      sleep 1
    fi
    \$0 start
    ;;
  *)
    echo "Usage: \$0 {start|stop|restart|force-reload|status}"
    exit 3
    ;;
esac
EOF


# Move files to doc extension
# mkdir -p $TMPDIR-doc/usr/local/share/${PACKAGE}

# mv ${DESTDIR}/usr/local/share/man ${TMPDIR}-doc/usr/local/share/${PACKAGE}/
# mv ${DESTDIR}/usr/local/share/doc ${TMPDIR}-doc/usr/local/share/${PACKAGE}/

























# Move files to dev extension
# mkdir -p $TMPDIR-dev/usr/local/

# mv ${DESTDIR}/usr/local/include ${TMPDIR}-dev/usr/local/























































###################################################
# Create base extension in temp dir               #
###################################################
find $TMPDIR/ -type d | xargs chmod -v 755;

find $TMPDIR | xargs file | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded

cd $TMPDIR
find $TMPDIR -perm 777 -exec chmod 755 {} \;
find $TMPDIR -perm 555 -exec chmod 755 {} \;
find $TMPDIR -perm 444 -exec chmod 644 {} \;
find $TMPDIR -perm 666 -exec chmod 644 {} \;
find $TMPDIR -perm 664 -exec chmod 644 {} \;
sudo chown -R root:root $TMPDIR

cd /mnt/mmcblk0p2/tce/submit/

# mksquashfs $TMPDIR ${PACKAGE}.tcz
mksquashfs $TMPDIR ${PACKAGE}.tcz

cd $TMPDIR
sudo sh -c "find usr -not -type d | sed 's/\(.*$\)/\/\1/g' > ${PACKAGE}.tcz.list"
sudo mv ../${PACKAGE}.tcz .
sudo mv ../${PACKAGE}.tcz.dep .
sudo mv ../${PACKAGE}.tcz.info .

# Create md5 file
sudo sh -c "md5sum ${PACKAGE}.tcz > ${PACKAGE}.tcz.md5.txt"

# Cleanup temp directory
sudo rm -r -f usr





















































