#!/bin/bash
# ==============================================================================
# title			:repomaster
# description		:Auto build, repository management script
# author		:Glenn Cady <theemahn@ultimateedition.info>
# date			:01/26/2013
# version		:1.7.1-8
# usage			:repomaster --help
# manual		:man repomaster
# notes			:See change-log below for further information.
# bash_version		:4.2.8(1)-release
# ==============================================================================
# Change-log: 1.7.1-8: Currently unreleased / unleashed
# ==============================================================================
#Let's snatch the folder that will handle processing...

CURRENT=$PWD

# some defaults
user="root"
suargs="-p"
force="no"
target=$1
ISDEB=$(echo "$1" | grep '.deb')
if [ $ISDEB == '' ]; then
FOLDER=${target%%.deb}
FOLDER=$FOLDER'/'
else
deb=$target
fi
if [ $ISDEB != '' ]; then
action=$(yad --width 300 --entry --title "Repomaster" \
    --image=gnome-shutdown \
    --button="gtk-ok:0" --button="gtk-close:1" \
    --text "Choose action:" \
    --entry-text \
    "Extract: $deb" "Lintian: $deb" "Exit")
ret=$?
execcommand=$(echo $action | cut -d ":" -f1)
#zenity --error --title "TheeMahn's deb extraction script" --text="$execcommand"
else
action=$(yad --width 300 --entry --title "Repomaster" \
    --image=gnome-shutdown \
    --button="gtk-ok:0" --button="gtk-close:1" \
    --text "Choose action:" \
    --entry-text \
    "Build: $deb.deb" "Clean: $deb/" "Autofix: $deb/" "Relax: $deb/" "DEBUG2: $CURRENT" "Exit")
ret=$?
execcommand=$(echo $action | cut -d ":" -f1)
fi


case $action in
    Extract*) cd $CURRENT; repomaster -e $deb | yad --width 780 --title "Extract: $deb in $CURRENT" --progress --pulsate --auto-close --auto-kill --button gtk-cancel:1; yad --width 780 --height 580 --text-info --show-uri --name="notes" --window-icon="text-editor" \
        --title=$"Extraction results of $deb" --button="gtk-close:1" \
        --editable --filename=$CURRENT/tar.log; rm -f $CURRENT/tar.log ;;
    Lintian*) cd $CURRENT; lintian $deb > tmp.txt | yad --width 780 --title "Lintian: $deb in $CURRENT" --progress --pulsate --auto-close --auto-kill --button gtk-cancel:1; yad --width 780 --height 580 --text-info --show-uri --name="notes" --window-icon="text-editor" \
        --title=$"Lintian results of $deb" --button="gtk-close:1" \
        --editable --filename=$CURRENT/tmp.txt; rm -f $CURRENT/tmp.txt ;;
    Build*) cd $CURRENT; repomaster -b $FOLDER/ | yad --width 780 --title "Build: $deb in $CURRENT" --progress --pulsate --auto-close --auto-kill --button gtk-cancel:1; yad --width 780 --height 580 --text-info --show-uri --name="notes" --window-icon="text-editor" \
        --title=$"Build results of $deb" --button="gtk-close:1" \
        --editable --filename=$CURRENT/$deb.errors; rm -f $CURRENT/$deb.errors ;;
    Clean*) 
        case $(wmctrl -m | grep Name) in
            *Openbox) cmd="openbox --exit" ;;
            *FVWM) cmd="FvwmCommand Quit" ;;
            *Metacity) cmd="gnome-save-session --kill" ;; 
            *) exit 1 ;;
        esac
        ;;
    *) exit 1 ;;        
esac
exit 0
# parse commandline   
if [[ $# -eq 0 ]]; then
    echo "Usage: ${0##*/} [-f] [-u user] [--] "
    exit 1
fi

OPTIND=1
while getopts u: opt; do
    case "$opt" in
        f) force="yes" ;;
        u) user="$OPTARG" ;;
    esac
done
shift $((OPTIND - 1))

cmd="$*"

if [[ $force != "no" ]]; then
    # check for sudo
    sudo_check=$(sudo -H -S -- echo SUDO_OK 2>&1 &)
    if [[ $sudo_check == "SUDO_OK" ]]; then
        eval sudo $cmd
        exit $?
    fi
fi

# get password
pass=$(yad --class="GSu" \
    --title="Password" \
    --text="Enter password for user <b>$user</b>:" \
    --image="dialog-password" \
    --entry --hide-text)
[[ -z "$pass" ]] && exit 1

# grant access to xserver for specified user
xhost +${user}@ &> /dev/null

# run command
fifo_in="$(mktemp -u --tmpdir gsu.empty.in.XXXXXXXXX)"
fifo_out="$(mktemp -u --tmpdir gsu.empty.out.XXXXXXXXX)"

LC_MESSAGES=C empty -f -i $fifo_in -o $fifo_out su $suargs $user -c "$cmd"
[[ $? -eq 0 ]] && empty -w -i $fifo_out -o $fifo_in "word:" "$pass\n"

exit $?

# Did the user select any file at all?
if [ $# == 0 ]; then
zenity --error --title "TheeMahn's deb extraction script" --text="You did not select a deb file 
for extraction."
exit
fi

# Try to cut past Nautilus bug concerning compression in the home directory
if [ $NAUTILUS_SCRIPT_CURRENT_URI == "x-nautilus-desktop:///" ]; then
   cd "$HOME/Desktop"
fi

# Functions
CheckFile() {
  if [ -f "$FOLDER" ]
then
  if ! zenity --question \
          --title "TheeMahn's deb extraction script" \
          --text="The folder \"$FOLDER\" already exists.

Do you want to overwrite it?"
  then
    exit
  fi
fi
} 

# Start main loop
for File in "$@"
do
CheckFile

#Build single Deb
echo "Building "$1
FILE=$1
target=$(echo "$FILE" | sed -e "s/ /_/")
deb="${target%/}.deb"
echo -e "${bldwht}================================="
echo "Beginning build of "$FILE
echo "================================="
echo "Relaxing permissions..."
(sudo chmod -R 777 $FILE) | 2>&1 zenity --progress \
--title="TheeMahn's deb builder - Stage 1" \
--text="Relaxing permissions on: $File" \
--percentage=0 \
--auto-close \
--pulsate
(find $FILE -type f -name "*~" -exec rm -f {} \;) | 2>&1 zenity --progress \
--title="TheeMahn's deb builder - Stage 2" \
--text="Cleaning up any backup files in: $File" \
--percentage=0 \
--auto-close \
--pulsate
(sudo chmod -R 777 $FILE) | 2>&1 zenity --progress \
--title="TheeMahn's deb builder - Stage 3" \
--text="Relaxing permissions on: $File" \
--percentage=0 \
--auto-close \
--pulsate
(find $FILE -type f -exec chmod 644 {} \;) | 2>&1 zenity --progress \
--title="TheeMahn's deb builder - Stage 3" \
--text="Relaxing permissions on: $File" \
--percentage=0 \
--auto-close \
--pulsate
(sudo chown -R $USER:$USER $FILE) | 2>&1 zenity --progress \
--title="TheeMahn's deb builder - Stage 2" \
--text="Changing ownership to root on: $File" \
--percentage=0 \
--auto-close \
--pulsate
cd $CURRENT
(find $FILE -name "DEBIAN" -prune -o -type f -exec sh -c 'test "$(head -c 2 "$1")" = "#!"' sh {} \; -print -exec chmod 755 {} \;) | 2>&1 zenity --progress \
--title="TheeMahn's deb builder - Stage 2" \
--text="Changing ownership to root on: $File" \
--percentage=0 \
--auto-close \
--pulsate
#echo -e "${bldgrn}Cleaning up any tmp or backup files."
#find $FILE -type f -name "*~" -exec rm -f {} \;
#echo "Setting individual file permissions to 644."

#echo "Scanning for executables."

#Test for executables & make naming conventions apply spaces etc.
#/usr/share/screenlets/Lyrics/Quodlibet plugin/LyricsScreenletInformator.py becomes /usr/share/screenlets/Lyrics/Quodlibet\ plugin/LyricsScreenletInformator.py to set the executable bit.
#Sed is hardcore, also handles many other nonstandard characters all in one line.  Why?  Because I sed so ;)
#first find executables and set executable.
find $FILE -name "DEBIAN" -prune -o -type f -exec sh -c 'test "$(head -c 2 "$1")" = "#!"' sh {} \; -print -exec chmod 755 {} \;
#No header, no problem
#find $FILE -name "*.sh" -exec chmod 755 {} \;
#find $FILE -name "*.py" -exec chmod 755 {} \;
#Nonstandard? spaces ( " etc.  sed 's/\([ "(){}$#\&~'"'"']\)/\\\1/g'
cd $FILE
#find . -name "DEBIAN" -prune -o -type f -exec sh -c 'test "$(head -c 2 "$1")" = "#!"' sh {} \; -print | sed 's/\([ "(){}$#\&~'"'"']\)/\\\1/g' > executables
#if test -s executables
#then
#echo "Non conforming executables found:"
#cat executables | while read EXE
#do
#	echo "Setting Executable bit for: "$EXE
#	chmod 755 $EXE
#done
#fi
#if test -f executables
#then
#rm executables
#fi
echo "Calculating MD5SUMS..."
find -name "DEBIAN" -prune -o -type f -exec md5sum {} + >DEBIAN/md5sums
cd $CURRENT
echo "Setting ownership to root."
sudo chown -R root:root $FILE
echo "Setting individual folder permissions to 755."
sudo find $FILE -type d -exec chmod 755 {} \;
echo "Changing folder to "$FILE"DEBIAN/"
cd $FILE/DEBIAN/
echo "Setting permissions rights for control etc."
sudo chmod 755 *
sudo chmod 644 md5sums
if test -f conffiles
then
sudo chmod 644 conffiles
fi
if test -f shlibs
then
sudo chmod 644 shlibs
fi
cd $CURRENT
echo "Beginning build of "$FILE
dpkg --build $FILE 2>>build.log
echo "Lintian resulting package "$deb"." 
lintian $deb 1> $deb.errors
if test -s "$deb.errors"
then
if grep -q 'E:' $deb.errors

    then
     cat $deb.errors >> all_errors.txt
     echo -e "${bldred}Error: please see the log file "$deb.errors
  else
     cat $deb.errors >> all_warnings.txt
     echo -e "${bldylw}Warning: possible issues in $deb please view "$deb.errors
     echo "Moving "$deb" to ../builds/"
     mv $deb ../builds/
  fi
else
  echo -e "${bldwht}We have compiled a perfect deb."
  rm $deb.errors
  echo "Moving "$deb" to ../builds/"
  mv $deb ../builds/
fi
rm tmp.txt
if test -s "build.log"
  then
    echo -e "${bldred}Error: A major issue has occured building one of the deb files.  Please see build.log and *.errors"
  else
    echo -e "${bldwht}Warnings may have been issued, but we have a totally successful build.  0 Errors."
    rm build.log
fi




(ar x "$File") | 2>&1 zenity --progress \
--title="TheeMahn's deb extraction script - Stage 1" \
--text="Extracting: $File" \
--percentage=0 \
--auto-close \
--pulsate

mkdir $FOLDER
rm debian-binary
mv control.tar.gz $FOLDER
cd $FOLDER
(tar xfv "control.tar.gz") | 2>&1 zenity --progress \
--title="TheeMahn's deb extraction script - Stage 2" \
--text="Extracting: $File" \
--percentage=0 \
--auto-close \
--pulsate
rm control.tar.gz
mkdir DEBIAN
mv * DEBIAN/
cd ..
mv data.tar.gz $FOLDER
cd $FOLDER
(tar xfv "data.tar.gz") | 2>&1 zenity --progress \
--title="TheeMahn's deb extraction script - Stage 3" \
--text="Extracting: $File" \
--percentage=0 \
--auto-close \
--pulsate

#clean up
rm data.tar.gz

done # Ok next file

