#!/bin/bash

set -e

# Stop
systemctl stop flan

# Install needed packages
apt-get update
apt-get upgrade -y
apt-get install -y xorg xinit xfonts-{base,100dpi} build-essential libx{11,pm}-dev

# Create config headers
cat << EOF > /tmp/config.h
#define REFRESH 3600
#define DAYS 3
#define LOGO "/usr/local/share/flan/flan/uakron.xpm"
#define TITLE "College of Business Computer Labs"
#define FONT_M "-*-helvetica-medium-r-normal-*-20-*-*-*-*-*-*-*"
#define FONT_A "-*-times-bold-r-normal-*-24-*-*-*-*-*-*-*"
#define FONT_L "-*-new century schoolbook-bold-r-normal-*-34-*-*-*-*-*-*-*"
#define FONT_D "-*-helvetica-medium-r-normal-*-17-*-*-*-*-*-*-*"
#define FONT_I "-*-new century schoolbook-medium-r-*-*-17-*-*-*-*-*-*-*"
#define REGEX "^(.+)[[:space:]]?--[[:space:]]?(.*)"
typedef struct {
    const char *left;
    const char *right;
} POS;
static const POS TXT[] = {
    { "Mo-Th: 8:30AM-8:30PM | Fr: 8:30AM-3:30PM | Sa-Su: Closed", "https://uakron.edu/business/ | 330-972-7036 | cobtechsupport@uakron.edu" },
    { NULL, NULL }
};
#define T_BGC "#4A6B8C"
#define T_TXT "#FFFFFF"
#define B_BGC "#CCD3D7"
#define B_TXT "#000000"
#define S_BGC "#3A5B71"
#define S_TXT "#E3E3E5"
#define C_BGC "#FFFFFF"
typedef struct {
    const char *name;
    const char *path;
} SRC;
static const SRC ICS[] = {
    { "101", "/opt/coblabs/cals/101.ics" },
    { "106", "/opt/coblabs/cals/106.ics" },
    { "176", "/opt/coblabs/cals/176.ics" },
    { NULL, NULL }
};
EOF

# Compile and install the Flan
cd /tmp/
wget ftp://antonm.org/software/flan/flan.c -O /tmp/flan.c
sed -i 's/default\.xpm/uakron\.xpm/g' /tmp/flan.c
mkdir -p /usr/local/share/flan/flan/
wget https://ucob.net/labs/uakron.xpm -O /usr/local/share/flan/flan/uakron.xpm
gcc -O3 -Wall -Wextra -D_FORTIFY_SOURCE=2 -fstack-protector-strong -Wl,--no-fatal-warnings -o /usr/local/bin/flan flan.c -lXpm -lX11 -lxcb -lXau -lXdmcp -ldl

# Create systemd service
cat << EOF > /etc/systemd/system/flan.service
[Unit]
Description=FLAN: Flan Local-Access Notifier
After=network-online.target remote-fs.target syslog.target
Wants=network-online.target

[Service]
Type=simple
ExecStartPre=-/usr/bin/fuser -k /dev/tty7
ExecStart=/usr/bin/xinit /usr/local/bin/flan -- vt7 -nocursor
StandardInput=tty
StandardOutput=tty
TTYPath=/dev/tty7
TTYReset=yes
TTYVHangup=yes

[Install]
WantedBy=multi-user.target
EOF

# Create X11 fix conf
cat << EOF > /etc/X11/xorg.conf.d/10-flan.conf
Section "ServerFlags"
    Option "BlankTime" "0"
    Option "StandbyTime" "0"
    Option "SuspendTime" "0"
    Option "OffTime" "0"
EndSection
Section "Extensions"
    Option "DPMS" "Disable"
EndSection
EOF

# Create cron job
cat << EOF > /etc/cron.d/flan
@reboot root sleep 15 && wget -qO- https://ucob.net/labs/cal.bash | bash
0 1,3,5,7,9,11,13,15,17,19,21,23 * * * root sleep 5 && wget -qO- https://ucob.net/labs/cal.bash | bash
EOF

/bin/chmod +x /etc/X11/xorg.conf.d/10-flan.conf
/bin/systemctl daemon-reload
/bin/systemctl enable --now flan
echo > /dev/null
