#!/bin/bash

# CopyCat is free software: you can redistribute it and/or modify
# it under the terms of WTFP Public License This program is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY.

PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin:/usr/local/bin:/usr/local/sbin
# Added for translation purposes
# i18n - Internationalisation - Internationalisierung
VERSION=2.0.3
export TEXTDOMAIN=copycat_$VERSION
export TEXTDOMAINDIR="/usr/share/locale"
# variable for the gui
EICON="/usr/share/copycat/icons/error.svg"
WICON="/usr/share/copycat/icons/warning.svg"
CANCEL="/usr/share/copycat/icons/cancel.svg"
OK="/usr/share/copycat/icons/ok.svg"

#-----------------------------------------------
# run as root
#-----------------------------------------------
PID=`ps -eaf | grep yad | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
  echo "killing $PID"
  kill -9 $PID > /dev/null 2>&1 &
fi
if [ `id -u` -eq 0 ]; then
exec $@
else
`yad --title="CopyCat" --width=400 \
--height=100 --fixed --image=$EICON \
--window-icon=$EICON --center \
--text=$"\n\You need to be root to run CopyCat!" \
--button=Ok!$OK:"1"`
if [ "$?" = "1" ] ; then
exit 1
 fi
fi
rm -f /tmp/copycat >/dev/null 2>&1

NVME=$(grep -o nvme /etc/mtab| awk 'NR==1{print $0}')
if [[ $NVME = "$NVME" ]]
then
lsblk | grep -o sd[a-z] | tail -n1 |awk '$0="/dev/"$0' > /tmp/copycat
sleep 0.50
USBdevice=$(grep -o sd[a-z] /proc/partitions |tail -n1)
lsblk -do VENDOR,MODEL,SIZE /dev/$USBdevice |sed -e 's/ \+/ /g'| awk 'NR == 2' >> /tmp/copycat
else
lsblk | grep -o sd[b-z] | tail -n1 |awk '$0="/dev/"$0' > /tmp/copycat
sleep 0.50
USBdevice=$(grep -o sd[a-z] /proc/partitions |tail -n1)
lsblk -do VENDOR,MODEL,SIZE /dev/$USBdevice |sed -e 's/ \+/ /g'| awk 'NR == 2' >> /tmp/copycat
fi
if [ -s "/tmp/copycat" ]; then
exec $@
else
USERS=$(who |sed 's/ .*//'|head -n1)
su $USERS -c /usr/share/copycat/info_notify.py
pkill -f /usr/bin/copycat >/dev/null 2>&1
sleep 1
pkexec /usr/bin/copycat 2>/dev/null
exit 1
  fi
# Check if the user remouted the usb key
CHMOUNT=$(grep -o "0B" /tmp/copycat)
if [[ "$CHMOUNT" == "" ]] ; then
exec $@
else
`yad --title="CopyCat" --width=450 --height=100 --fixed --center --image=$WICON \
--window-icon=$WICON --center \
--text=$"\n\Remount the USB Device so it can be detected?\n<span color=\"#e07b39\">Continue only when the USB Device has been Inserted.</span>" \
--button=Cancel!$CANCEL:"1"`
if [ $? = 1 ] ; then
pkill -SIGKILL copycat-iso >/dev/null 2>&1
exit
   fi
    fi

python3 /usr/share/copycat/copycat.py -m iso "$@"
