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

######################################################
# Prepare extension creation                         #
######################################################
#download and install dependencies
tce-load -wi bash.tcz
tce-load -wi python3.11.tcz
tce-load -wi python3.11-setuptools.tcz
tce-load -wi python3.11-pip.tcz
tce-load -wi patch.tcz
tce-load -wi xz.tcz
tce-load -wi curl.tcz
#download and install the compile tools
tce-load -wi binutils
tce-load -wi git.tcz
tce-load -wi go.tcz
tce-load -wi go-doc.tcz
tce-load -wi compiletc.tcz
tce-load -wi squashfs-tools.tcz

######################################################
# Configure extension creation parameters            #
######################################################
# Variables
TODAY=`date +%Y/%m/%d`
PACKAGE="grafana"
VERSION="11.4.0"
DESCRIPTION="Grafana OSS, open source data visualization and monitoring solution"
DOCDESCRIPTION="Documentation part of Grafana OSS"
DEVDESCRIPTION="Development files part of Grafana OSS"
AUTHORS="contact@grafana.com"
HOMEPAGE="https://grafana.com"
LICENSE="AGPLv3"
ME="rhermsen"
TAGS="grafana data visualization"
DOCTAGS="man pages grafana data visualization"
DEVTAGS="development grafana data visualization"
DESTDIR=/mnt/mmcblk0p2/tce/dest/${PACKAGE}
TMPDIR=/mnt/mmcblk0p2/tce/submit/${PACKAGE}
SRCDIR=/mnt/mmcblk0p2/tce/src/${PACKAGE}
ARCH=`uname -m`


# Go
[ ! -d  $SRCDIR ] && mkdir -p $SRCDIR
export SOURCE_ROOT=$SRCDIR
[ ! -d  /mnt/mmcblk0p2/go ] && sudo mkdir /mnt/mmcblk0p2/go
cd /mnt/mmcblk0p2
sudo chown tc:staff go
export GOPATH=/mnt/mmcblk0p2/go
[ ! -d  /mnt/mmcblk0p2/go-build ] && sudo mkdir /mnt/mmcblk0p2/go-build
cd /mnt/mmcblk0p2
sudo chown tc:staff go-build
go clean -cache
go clean -fuzzcache
export GOCACHE=/mnt/mmcblk0p2/go-build
[ ! -d  /mnt/mmcblk0p2/tmp ] && sudo mkdir /mnt/mmcblk0p2/tmp
cd /mnt/mmcblk0p2
sudo chown tc:staff tmp
cd /mnt/mmcblk0p2/tmp
sudo rm -r go-build*
export GOTMPDIR=/mnt/mmcblk0p2/tmp
cd $SOURCE_ROOT
sudo rm -r grafana
git clone --depth=1 --single-branch -b v11.4.0 https://github.com/grafana/grafana.git
cd grafana

go env


######################################################
# 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"
# no specific arch dependent parameters
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
# no specific arch dependent parameters
else
exit 1
fi
export LDFLAGS="-Wl,-O1"
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:/usr/lib/pkgconfig

# Compile
# Build Grafana Backend
cd $SOURCE_ROOT/grafana
time go mod download
time make build-go

# Download and install the Grafana distribution to get the pre-built frontend files
cd $SOURCE_ROOT
sudo rm -r grafana-dist
[ ! -f  $SOURCE_ROOT/${PACKAGE}-${VERSION}.linux-arm64.tar.gz ] && wget https://dl.grafana.com/oss/release/grafana-${VERSION}.linux-arm64.tar.gz
mkdir grafana-dist
tar -x -C grafana-dist --strip-components=1 -f grafana-${VERSION}.linux-arm64.tar.gz
rm grafana-dist/bin/*
cp  $SOURCE_ROOT/grafana/bin/linux-arm64/grafana $SOURCE_ROOT/grafana-dist/bin/
cp  $SOURCE_ROOT/grafana/bin/linux-arm64/grafana-server $SOURCE_ROOT/grafana-dist/bin/
cp  $SOURCE_ROOT/grafana/bin/linux-arm64/grafana-cli $SOURCE_ROOT/grafana-dist/bin/

# 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/sbin
mkdir -p  ${TMPDIR}/usr/local/share/${PACKAGE}
mkdir -p  ${TMPDIR}/usr/local/etc/${PACKAGE}
mkdir -p  ${TMPDIR}/usr/local/etc/init.d/
mkdir -p  ${TMPDIR}/usr/local/share/doc/${PACKAGE}
mkdir -p ${TMPDIR}/usr/local/tce.installed

mv ${SRCDIR}/${PACKAGE}-dist/bin/grafana ${TMPDIR}/usr/local/bin
mv ${SRCDIR}/${PACKAGE}-dist/bin/grafana-cli ${TMPDIR}/usr/local/bin
mv ${SRCDIR}/${PACKAGE}-dist/bin/grafana-server ${TMPDIR}/usr/local/bin
mv ${SRCDIR}/${PACKAGE}-dist/Dockerfile ${TMPDIR}/usr/local/share/${PACKAGE}/
mv ${SRCDIR}/${PACKAGE}-dist/conf ${TMPDIR}/usr/local/share/${PACKAGE}/
mv ${SRCDIR}/${PACKAGE}-dist/docs ${TMPDIR}/usr/local/share/${PACKAGE}/
mv ${SRCDIR}/${PACKAGE}-dist/npm-artifacts ${TMPDIR}/usr/local/share/${PACKAGE}/
# mv ${SRCDIR}/${PACKAGE}-dist/packaging ${TMPDIR}/usr/local/share/${PACKAGE}/
mv ${SRCDIR}/${PACKAGE}-dist/plugins-bundled ${TMPDIR}/usr/local/share/${PACKAGE}/
mv ${SRCDIR}/${PACKAGE}-dist/public ${TMPDIR}/usr/local/share/${PACKAGE}/
mv ${SRCDIR}/${PACKAGE}-dist/tools ${TMPDIR}/usr/local/share/${PACKAGE}/

# mv ${SRCDIR}/${PACKAGE}-dist/packaging/deb/init.d ${TMPDIR}/usr/local/etc/
mv ${SRCDIR}/${PACKAGE}-dist/packaging/deb/default ${TMPDIR}/usr/local/etc/${PACKAGE}
mv  ${SRCDIR}/${PACKAGE}-dist/packaging/wrappers/* ${TMPDIR}/usr/local/sbin
cp ${SRCDIR}/${PACKAGE}/LICENSE ${TMPDIR}/usr/local/share/doc/${PACKAGE}/

###################################################                                      
# Create init-functions file                                #
###################################################
#/lib/lsb/init-functions
mkdir -p $TMPDIR/usr/local/lib/${PACKAGE}
cat <<EOF> $TMPDIR/usr/local/lib/${PACKAGE}/init-functions
#!/usr/local/bin/bash

log_success_msg () {
    echo "\$@" >&2
    [ -x /usr/bin/logger ] && echo "\$@" \\
        | /usr/bin/logger -t ${PACKAGE} -p daemon.info "\$@"
}

log_failure_msg () {
    echo "\$@" >&2
    [ -x /usr/bin/logger ] && echo "\$@" \\
        | /usr/bin/logger -t ${PACKAGE} -p daemon.err "\$@"
}

log_warning_msg () {
    echo "\$@" >&2
    [ -x /usr/bin/logger ] && echo "\$@" \\
        | /usr/bin/logger -t ${PACKAGE} -p daemon.warn "\$@"
}

log_daemon_msg () {
    echo "\$@" >&2
    [ -x /usr/bin/logger ] && echo "\$@" \\
        | /usr/bin/logger -t ${PACKAGE} -p daemon.info "\$@"
}

log_begin_msg () {
    echo "\$@" >&2
    [ -x /usr/bin/logger ] && echo "\$@" \\
        | /usr/bin/logger -t ${PACKAGE} -p daemon.info "\$@"
}

log_progress_msg () {
    echo "\$@" >&2
    [ -x /usr/bin/logger ] && echo "\$@" \\
        | /usr/bin/logger -t ${PACKAGE} -p daemon.info "\$@"
}

log_end_msg () {
    echo "\$@" >&2
    if [ -x /usr/bin/logger ]; then
        if [ "\$1" -eq 0 ]; then
            /usr/bin/logger -t ${PACKAGE} -p daemon.info "."
        elif [ "\$1" -eq 255 ]; then
            /usr/bin/logger -t ${PACKAGE} -p daemon.warn "(warning)."
        else
            /usr/bin/logger -t ${PACKAGE} -p daemon.err "(failed)!"
        fi
    fi
}
EOF

##################################################
# default file                                   #
################################################## 
mv ${TMPDIR}/usr/local/etc/grafana/default/grafana-server ${TMPDIR}/usr/local/etc/grafana/default/grafana
sed -i 's/GRAFANA_USER=grafana/GRAFANA_USER=tc/g' ${TMPDIR}/usr/local/etc/grafana/default/grafana
sed -i 's/GRAFANA_GROUP=grafana/GRAFANA_GROUP=staff/g' ${TMPDIR}/usr/local/etc/grafana/default/grafana
sed -i 's/GRAFANA_HOME=\/usr\/share\/grafana/GRAFANA_HOME=\/usr\/local\/share\/grafana/g' ${TMPDIR}/usr/local/etc/grafana/default/grafana
sed -i 's/CONF_DIR=\/etc\/grafana/CONF_DIR=\/usr\/local\/etc\/grafana/g' ${TMPDIR}/usr/local/etc/grafana/default/grafana
sed -i 's/CONF_FILE=\/etc\/grafana\/grafana.ini/CONF_FILE=$CONF_DIR\/grafana.ini/g' ${TMPDIR}/usr/local/etc/grafana/default/grafana
sed -i 's/PROVISIONING_CFG_DIR=\/etc\/grafana\/provisioning/PROVISIONING_CFG_DIR=$CONF_DIR\/provisioning/g' ${TMPDIR}/usr/local/etc/grafana/default/grafana
sed -i 's/PID_FILE_DIR=\/run\/grafana/PID_FILE_DIR=\/var\/run\/grafana/g' ${TMPDIR}/usr/local/etc/grafana/default/grafana

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

NAME=grafana
DESC="Grafana Server"
DEFAULT=/usr/local/etc/grafana/default/\$NAME

GRAFANA_USER=tc
GRAFANA_GROUP=staff
GRAFANA_HOME=/usr/local/share/grafana
CONF_DIR=/usr/local/etc/grafana
WORK_DIR=\$GRAFANA_HOME
DATA_DIR=/var/lib/grafana
PLUGINS_DIR=/var/lib/grafana/plugins
LOG_DIR=/var/log/grafana
CONF_FILE=\$CONF_DIR/grafana.ini
PROVISIONING_CFG_DIR=\$CONF_DIR/provisioning
MAX_OPEN_FILES=10000
PID_FILE=/var/run/\$NAME.pid
DAEMON=/usr/local/bin/grafana

umask 0027

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

. /usr/local/lib/grafana/init-functions

if [ -r /etc/default/rcS ]; then
  . /etc/default/rcS
fi

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

# DAEMON_OPTS="server --pidfile=\${PID_FILE} --config=\${CONF_FILE} cfg:default.paths.provisioning=\$PROVISIONING_CFG_DIR cfg:default.paths.data=\${DATA_DIR} cfg:default.paths.logs=\${LOG_DIR} cfg:default.paths.plugins=\${PLUGINS_DIR}"
# If the pidfile is not part of the grafana server parameters it will not try to interact with it.
DAEMON_OPTS="server --config=\${CONF_FILE} cfg:default.paths.provisioning=\$PROVISIONING_CFG_DIR cfg:default.paths.data=\${DATA_DIR} cfg:default.paths.logs=\${LOG_DIR} cfg:default.paths.plugins=\${PLUGINS_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
    log_daemon_msg "Starting \$DESC"
    pid="\`cat \$PID_FILE 2>/dev/null\`"
    if [ -n "\$pid" ] ; then
      log_begin_msg "Already running."
      log_end_msg 0
      exit 0
    fi

    # Prepare environment
    [ ! -d \$LOG_DIR ] && mkdir -p "\$LOG_DIR"
    [ ! -d \$DATA_DIR ] && mkdir -p "\$DATA_DIR"
    chown "\$GRAFANA_USER":"\$GRAFANA_GROUP" "\$LOG_DIR" "\$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 "\$GRAFANA_USER":"\$GRAFANA_GROUP" "\$PID_FILE"
    # The file should be world readable
    chmod 644 "\$PID_FILE"

    if [ -n "\$MAX_OPEN_FILES" ]; then
      ulimit -n \$MAX_OPEN_FILES
    fi

    # Start Daemon
    sleep 3
    cd "\$GRAFANA_HOME"
    start-stop-daemon -S -n "\$NAME" -x \$DAEMON -p "\$PID_FILE" -b -m -v -c "\$GRAFANA_USER":"\$GRAFANA_GROUP" -- \$DAEMON_OPTS
    sleep 1
    if ! [[ -s \$PID_FILE ]]
    then
      log_end_msg 1
      rm -f "\${PID_FILE}"
      exit 1
    else
      log_begin_msg "\$DESC started."
      log_end_msg 0
    fi
    ;;
  stop)
    checkUser
    log_daemon_msg "Stopping \$DESC"

    if [ -f "\$PID_FILE" ]; then
      start-stop-daemon -K -n "\$NAME" -p "\$PID_FILE" -s TERM
      sleep 1
      pid=\`pidof \$NAME\`
      if [ -n "\$pid" ] ; then
        log_failure_msg "Failed to stop \$DESC (pid \$PID)"
      else
        log_progress_msg "\$DESC is not running but pid file exists, cleaning up"
        rm -f "\${PID_FILE}"
      fi
    else
      pid=\`pidof \$NAME\`
      if [ -n "\$pid" ] ; then
        start-stop-daemon -K -n \${NAME} -x \${DAEMON} -s TERM
      else
        log_progress_msg "(not running)"
      fi
    fi
    log_end_msg 0
    ;;
  status)
    pid=\`pidof \$NAME\`
    PID=\`cat \$PID_FILE 2>/dev/null\` 
    if [[ -s \$PID_FILE ]]; then
        if [[ "\$pid" == "\$PID" ]]; then
          log_progress_msg  " \${DAEMON} (pid \$pid) is running ..."
        else
          log_progress_msg "\${DAEMON} is not running but a PID file exist (\$PID_FILE = \$PID)"
        fi
    else
      if [ ! -z "\$pid" ] ; then
        log_progress_msg "\${DAEMON} is running but no PID file exist (PID = \$pid)"
      else
       log_progress_msg "\${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




















































###################################################
# 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:       Grafana allows you to query, visualize, alert on and
                understand your metrics no matter where they are stored.
                Create, explore, and share dashboards with your team and 
                foster a data-driven culture:
                - **Visualizations:** Fast and flexible client side graphs with
                a multitude of options. Panel plugins offer many different
                ways to visualize metrics and logs.
                - **Dynamic Dashboards:** Create dynamic & reusable
                dashboards with template variables that appear as 
                dropdowns at the top of the dashboard.
                - **Explore Metrics:** Explore your data through ad-hoc
                queries and dynamic drilldown. Split view and compare
                different time ranges, queries and data sources side by side.
                - **Explore Logs:** Experience the magic of switching from
                metrics to logs with preserved label filters. Quickly search
                through all your logs or streaming them live.
                - **Alerting:** Visually define alert rules for your most
                important metrics. Grafana will continuously evaluate and
                send notifications to systems like Slack, PagerDuty,
                VictorOps, OpsGenie.
                - **Mixed Data Sources:** Mix different data sources in the
                same graph! You can specify a data source on a per-query
                basis. This works for even custom datasources.

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:       Grafana allows you to query, visualize, alert on and
                understand your metrics no matter where they are stored.
                Create, explore, and share dashboards with your team and 
                foster a data-driven culture:
                - **Visualizations:** Fast and flexible client side graphs with
                a multitude of options. Panel plugins offer many different
                ways to visualize metrics and logs.
                - **Dynamic Dashboards:** Create dynamic & reusable
                dashboards with template variables that appear as 
                dropdowns at the top of the dashboard.
                - **Explore Metrics:** Explore your data through ad-hoc
                queries and dynamic drilldown. Split view and compare
                different time ranges, queries and data sources side by side.
                - **Explore Logs:** Experience the magic of switching from
                metrics to logs with preserved label filters. Quickly search
                through all your logs or streaming them live.
                - **Alerting:** Visually define alert rules for your most
                important metrics. Grafana will continuously evaluate and
                send notifications to systems like Slack, PagerDuty,
                VictorOps, OpsGenie.
                - **Mixed Data Sources:** Mix different data sources in the
                same graph! You can specify a data source on a per-query
                basis. This works for even custom datasources.

Change-log:     ${TODAY} First version, ${VERSION} (${ME})
Current:        ${TODAY} First version, ${VERSION} (${ME})
EOF
fi

###################################################                            
# Create .dep file                                #
###################################################
cat <<EOF> ${PACKAGE}.tcz.dep
bash.tcz
node.tcz
EOF

###################################################
# Create install script file                      #
###################################################
cat <<EOF> $TMPDIR/usr/local/tce.installed/${PACKAGE}
#!/bin/sh
rm -r /usr/local/share/${PACKAGE}/public
cp -r /tmp/tcloop/grafana/usr/local/share/${PACKAGE}/public  /usr/local/share/${PACKAGE}
chown -R tc:staff /usr/local/share/${PACKAGE}
[ ! -d /var/lib/grafana/plugins ] && mkdir -p /var/lib/grafana/plugins
chown -R tc:staff /var/lib/${PACKAGE}/plugins
grep -qF "var/lib/grafana" /opt/.filetool.lst || echo "var/lib/grafana"  >> /opt/.filetool.lst
if [ -r /usr/local/etc/${PACKAGE}/${PACKAGE}.ini ]; then
        echo "After a version upgrade verify if /usr/local/etc/${PACKAGE}/${PACKAGE}.ini requires changes." | tee /dev/null
        echo "See /usr/local/share/${PACKAGE}/conf/sample.ini for the latest example." | tee /dev/null
else
        cp /usr/local/share/${PACKAGE}/conf/sample.ini  /usr/local/etc/${PACKAGE}/${PACKAGE}.ini
        chown -R tc:staff /usr/local/etc/${PACKAGE}
        grep -qF "usr/local/etc/grafana" /opt/.filetool.lst || echo "usr/local/etc/grafana"  >> /opt/.filetool.lst
fi
EOF

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

# mv ${SRCDIR}/grafana/doc ${TMPDIR}-doc/usr/local/share/${PACKAGE}/
# mv ${SRCDIR}/usr/share/${PACKAGE}/docs ${TMPDIR}-doc/usr/local/share/${PACKAGE}/










































###################################################
# 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 {} \;
chmod 755 $TMPDIR/usr/local/lib/grafana/init-functions
chmod 644 $TMPDIR/usr/local/share/grafana/public/img/transformations/dark/*.svg
chmod 644 $TMPDIR/usr/local/share/grafana/public/img/transformations/light/*.svg
chmod 644 $TMPDIR/usr/local/share/grafana/docs/sources/shared/tutorials/create-plugin.md
# chmod 644 $TMPDIR/usr/local/share/grafana/packages/grafana-ui/src/themes/GlobalStyles/extra.ts
chmod -R 775 $TMPDIR/usr/local/tce.installed
sudo chown -R root:root $TMPDIR
sudo chown -R root:staff $TMPDIR/usr/local/tce.installed
sudo chown -R root:staff $TMPDIR/usr/local/etc/grafana

cd /mnt/mmcblk0p2/tce/submit/

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



























