#!/bin/bash

##################################################
# Mount dir                                      #
# - LOG_DIR                                      #
# - DATA_DIR                                     #
##################################################

set -euo pipefail
export LANG=en_US.UTF-8
trap Quit EXIT

PIDS=
GOT_SIGTERM=
LOG_DIR=/var/log/cloudreve
DATA_DIR=/var/lib/cloudreve
SOCK_FILE=/sock/cloudreve
CONF_FILE=$DATA_DIR/cloudreve.ini

function Print {
    local file=/dev/null
    [ '-f' = "$1" ] && file=$2 && shift && shift
    date +"[%F %T] $*" | tee -a $file
}

function Quit {
    Print killing cloudreve ...
    while :; do
        pkill -f cloudreve && Print killing cloudreve ... || break
        sleep 1
    done
    Print Container stopped.
    test -n "$GOT_SIGTERM"
}

function ModifyConf {
    Print Generating $CONF_FILE ...
    cat > $CONF_FILE <<-EOF
[System]
Debug = false
Mode = master
Listen = :80
SessionSecret = $(date +%F | sha256sum | cut -c -64)
HashIDSalt = $(date +%T | sha256sum | cut -c -64)

#[UnixSocket]
#Listen = $SOCK_FILE
#Perm = 0666

[Database]
DBFile = $DATA_DIR/cloudreve.db
#Type = mysql
#Port = 3306
#User = cloudreve
#Password = Cloudreve_1234
#Host = 127.0.0.1
#Name = cloudreve
#TablePrefix = cd_
#Charset = utf8mb4

#[Redis]
#Server = 127.0.0.1:6379
#Password = 123456
#DB = 9

#[CORS]
#AllowOrigins = *
#AllowMethods = OPTIONS,GET,POST
#AllowHeaders = *
#AllowCredentials = false
EOF
}

function StartProc {
    Print Starting cloudreve ...
    cd $DATA_DIR
    /opt/cloudreve -c cloudreve.ini &>> $LOG_DIR/cloudreve.out &
    PIDS="$PIDS $!"
    sleep 8
    [ -e $SOCK_FILE ] && chmod 0666 $SOCK_FILE
    Print Cloudreve started.
}

function Main {
    local pid=
    [ -e $CONF_FILE ] || ModifyConf
    StartProc
    trap "GOT_SIGTERM=1; Print Got SIGTERM ..." SIGTERM
    while [ -z "$GOT_SIGTERM" ] && sleep 2; do
        for pid in $PIDS; do
            [ ! -e /proc/$pid ] && Print Unexpected error! && exit
        done
    done
}

# Start here
Main

