#!/bin/sh
# File: /usr/bin/makemkv-wrapper
# Author: bgstack15
# Startdate: 2019-02
# Title: Wrapper for MakeMKV
# Purpose: To adjust time so MakeMKV will work with a specific keycode
# Package: makemkv from stackrpms
# History:
# Usage:
# Reference:
# Improve:
#    Detect if chronyc or ntpdate and use which one is available. Prefer ntpdate.
# Documentation:
# Dependencies:
#    systemctl, ntpdate, ntpd | chronyd, makemkv, bup (bgscripts-core), date, cp

# verify dependencies
test ! -e "$( sudo which ntpdate )" && { echo "need ntpdate. Aborted." ; exit 1 ; }

# vars
MW_GOODDATE="2019-02-27 13:38:55"
MW_NTPSERVICE="$( sudo systemctl list-units | awk '/ntp|chrony/{print $1}' | head -n1 )"
MW_GOOD_KEYFILE="$( find /usr/share/doc -ipath '*/makemkv/*' -name 'settings.conf.example' )"
MW_KEYFILE=~/.MakeMKV/settings.conf

# change date to known good date
MW_currentdate="$( date '+%F %T' )"
sudo systemctl stop "${MW_NTPSERVICE}"
sudo date -s "${MW_GOODDATE}"

# copy in valid key for the date in question
# ensure directory exists, just in case this is first run
mkdir -p "$( dirname "${MW_KEYFILE}" )"
diff -q "${MW_KEYFILE}" "${MW_GOOD_KEYFILE}" 1>/dev/null 2>&1 || bup "${MW_KEYFILE}"
/bin/cp -pf "${MW_GOOD_KEYFILE}" "${MW_KEYFILE}"

# run application and wait for it to observe the time
makemkv &
echo "Press enter in this terminal to set clock back to correct time. Do this when you have already started the dvd export."
read foo

# restore original date
sudo date -s "${MW_currentdate}"
sudo ntpdate dns1
sudo systemctl start "${MW_NTPSERVICE}"