#!/bin/bash
# mkdosswapfile - create KNOPPIX swapfile on a existing DOS/NTFS partition
# (C) Klaus Knopper Mar 2001
# 번역 : 서민구, 신재훈
# gdialog로 출력 변환 : 신재훈

PATH="/bin:/sbin:/usr/bin:/usr/sbin"
export PATH

XDIALOG_HIGH_DIALOG_COMPAT=1
export XDIALOG_HIGH_DIALOG_COMPAT

[ "`id -u`" != "0" ] && exec sudo "$0" "$@"

TMP="/tmp/mkdosswapfile.tmp$$"

IMAGE=""

bailout(){
rm -f "$TMP"
[ -n "$IMAGE" ] && umount `dirname "$IMAGE"` 2>/dev/null
exit 0
}

findfreeloop(){
i=0
for i in 0 1 2 3 4 5 6 7; do
LOOP="/dev/loop$i"
losetup "$LOOP" >/dev/null 2>&1 || { echo "$LOOP"; return 0; }
done
return 1
}


DIALOG="gdialog"
[ -n "$DISPLAY" ] && [ -x /usr/bin/gdialog ] && DIALOG="gdialog"

trap bailout 1 2 3 15

# LANGUAGE etc.
[ -f /etc/sysconfig/knoppix ] && . /etc/sysconfig/knoppix
[ -z "$LANG" ] && export LANG
[ -z "$LANGUAGE" ] && export LANGUAGE
[ -z "$CHARSET" ] && export CHARSET

# Find all usable partitions
# Build partition selector
PARTITIONS=""
count=0
for i in `awk '/^\/dev\/([hs]d|ub)[a-z].*\/mnt\/([hs]d|ub)[a-z]/{print $1}' /etc/fstab`; do
 fstype="$(awk "/^${i//\//\\/} /"'{print $3;exit}' /etc/fstab)"
 case "$fstype" in reiserfs|ext3|ext2|xfs|vfat|ntfs) ;; *) continue ;; esac
 size="$(awk '{if($NF=="'"${i##*/}"'"){print $3; exit}}' /proc/partitions)" # kB
 size="$((size/1024))MB" # MB
 PARTITIONS[$((count++))]="${i}"
 case "$i" in
  *hda*) PARTITIONS[$((count++))]="IDE  HD Partition [$fstype] ($size)" ;;
  *sda*) PARTITIONS[$((count++))]="SCSI HD Partition [$fstype] ($size)" ;;
  *uba*) PARTITIONS[$((count++))]="USB  HD Partition [$fstype] ($size)" ;;
      *) PARTITIONS[$((count++))]="Unknown [$fstype] ($size)" ;;
 esac
 PARTITIONS[$((count++))]="off"
done

if [ -z "$PARTITIONS" ]; then
case "$LANGUAGE" in
de|at|ch)
ERROR2="Leider sind auf Ihrem System keine geeigneten Partitionen zum Einrichten eines Swapfile vorhanden."
;;
es)
ERROR2="Lo siento, no se han encontrado particiones disponibles de tipo DOS para el fichero swap de memoria virtual."
;;
ko)
ERROR2="스왑파일로 사용할 수 있는 파티션이 없습니다."
;;
*)
ERROR2="Sorry, no usable partitions available for swapfile."
;;
esac
$DIALOG --msgbox "$ERROR2" 10 45
fi

# Language-dependent Messages
case "$LANGUAGE" in
de|at|ch)
MESSAGE1="Mchten Sie eine SWAP-Datei 'knoppix.swp' fr KNOPPIX auf einer bestehenden Partition anlegen? Eine solche SWAP-Datei ermglicht es Ihnen, trotz geringem Hauptspeicher Programmpakete wie KDE oder OpenOffice zu benutzen. Sie knnen diese Datei nach Beendigung Ihrer KNOPPIX-Session gefahrlos wieder lschen."
MESSAGE2="Bitte geben Sie an, wieviel MB Sie als SWAP verwenden wollen. Empfohlen: 60 - 128. Frei: "
MESSAGE3="Erzeuge swapfile 'knoppix.swp' auf $p..."
MESSAGE4="Dies ist eine NTFS-Partition. Da es hierfr vom Hersteller keinen Linux-Support gibt, der das direkte Schreiben auf die Partition ermglichen wrde, mssen Sie zunchst von Windows(TM) aus eine leere Image-Datei einrichten. Ein Programm hierfr finden Sie im Verzeichnis KNOPPIX auf Ihrer CD."
MESSAGE6="Dieses Image ist gerade in Benutzung, daher kann es nicht gelscht werden! Bitte booten Sie ggf. Knoppix neu, OHNE das Image $IMAGE einzubinden."
MESSAGE7="Hier befindet sich bereits eine KNOPPIX.SWP-Datei. Mchten Sie die Datei formatieren und neu einrichten?
NEIN=Abbruch"
MESSAGE8="Diese Partition lsst sich momentan nicht im Lese/Schreibmodus einbinden. Das Programm beendet sich."
ERROR0="Leider konnte die Partition NICHT eingebunden werden:"
ERROR1="Leider ist nicht genug Platz auf dieser Partition ($p), es sollten mindestens 60 MB frei sein."
SUCCESS="Das Einrichten des Swapfiles 'knoppix.swp' auf $p war erfolgreich."
;;
es)
MESSAGE1="Quiere crear un fichero de memoria virtual (swap) 'knoppix.swp' en particin existente? Un fichero swap le permite utilizar grandes aplicaciones como KDE incluso si su ordenador tiene poca memoria. Puede borrar tranquilamente el fichero swap una vez haya finalizado su sesin con KNOPPIX."
MESSAGE2="Por favor, especifique la cantidad de espacio en disco que quiere utilizar como SWAP. Recomendado: 60 - 128. Libre: "
MESSAGE3="Creando archivo de memoria virtual 'knoppix.swp' en $p..."
MESSAGE4="This is an NTFS partition. Because there is no vendor support for Linux that would allow writing directly to such a file system, you will first have to create an empty image file from within Windows(TM). You can find a program for this in the KNOPPIX directory on your CD."
MESSAGE6="This image is currently in use. If you want to delete/reformat it, please reboot Knoppix first, without activating the image $IMAGE."
MESSAGE7="There is already a KNOPPIX.SWP image present on this partition. Would like to delete/format it?
NO=Cancel"
MESSAGE8="This harddisk partition cannot be mounted in read-write mode currently, sorry."
ERROR0="Unfortunately, the partition could NOT be mounted:"
ERROR1="Lo siento, no hay suficiente espacio libre en $p. Son necesarios al menos 60 MB."
SUCCESS="Archivo swap 'knoppix.swp' en $p creado satisfactoriamente."
;;
ko)
MESSAGE1="'knoppix.swp'라는 스왑파일을 DOS 파티션 $p에 생성하시겠습니까? 스왑파일은 컴퓨터의 메모리가 적더라도, KDE와 같은 큰 응용프로그램을 사용할 수 있게 해줍니다. KNOPPIX 세션이 끝난 후 안전하게 스왑파일을 지울 수 있습니다."
MESSAGE2="스왑으로 사용하기 원하는 디스크영역의 용량을 정해주십시요. 추천: 60-128. 사용가능:"
MESSAGE3="스왑파일 'knoppix.swp'를 $p에 생성중..."
MESSAGE4="NTFS 파티션입니다. 리눅스는 NTFS 파일시스템에 쓰기 동작을 수행하는데 필요한 벤더로부터의 지원이 없으므로, 먼저 Windows(TM)에서 비어있는 이미지 파일을 생성해야합니다. CD안에 있는 KNOPPIX 디렉토리에서 여기에 필요한 프로그램을 찾을 수 있습니다."
MESSAGE6="현재 사용중인 이미지입니다. 만약 이 이미지를 삭제/포맷 하고 싶다면, $IMAGE 이미지를 비활성화 한 상태에서 Knoppix를 재부팅 하십시오."
MESSAGE7="이 파티션에 KNOPPIX.SWP 이미지가 이미 존재합니다. 파티션을 삭제하고 포맷하시겠습니까?
NO=취소"
MESSAGE8="이 하드디스크 파티션은 현재 읽기-쓰기 모드로 마운트될 수 없습니다."
ERROR0="파티션을 마운트할 수 없습니다."
ERROR1="$p에 공간이 충분하지 않습니다. 최소 60MB가 필요합니다."
SUCCESS="$p에 스왑파일 'knoppix.swp'가 성공적으로 생성되었습니다."
PARTINFO="파티션정보"
;;
*)
MESSAGE1="Do you want to create a swapfile 'knoppix.swp' on your existing DOS partition $p? A swapfile allows you to use huge application packages like KDE even if your computer is low on memory. You can safely delete the swapfile after finishing your KNOPPIX session."
MESSAGE2="Please specify the amount of diskspace that you want to use as SWAP. Recommended: 60 - 128. Free: "
MESSAGE3="Creating swapfile 'knoppix.swp' on $p..."
MESSAGE4="This is an NTFS partition. Because there is no vendor support for Linux that would allow writing directly to such a file system, you will first have to create an empty image file from within Windows(TM). You can find a program for this in the KNOPPIX directory on your CD."
MESSAGE6="This image is currently in use. If you want to delete/reformat it, please reboot Knoppix first, without activating the image $IMAGE."
MESSAGE7="There is already a KNOPPIX.SWP image present on this partition. Would like to delete/format it?
NO=Cancel"
MESSAGE8="This harddisk partition cannot be mounted in read-write mode currently, sorry."
ERROR0="Unfortunately, the partition could NOT be mounted:"
ERROR1="Sorry, not enough free space on $p. At least 60 MB required."
SUCCESS="Swapfile 'knoppix.swp' on $p successfully created."
;;
esac


DIRECTORY=""
PARTITION=""
while [ -z "$PARTITION" -o -z "$DIRECTORY" -o ! -e "$DIRECTORY" ]; do
rm -f "$TMP"
$DIALOG --msgbox "$MESSAGE1" 18 75
#$DIALOG --cr-wrap --clear --radiolist "PARTITIONS" 18 75 "${PARTITIONS[@]}" 2>"$TMP" || bailout
$DIALOG --cr-wrap --clear --radiolist "$PARTINFO" 18 75 9 "${PARTITIONS[@]}" 2>"$TMP" || bailout
PARTITION="$(<$TMP)"
DIRECTORY="/mnt/${PARTITION##/dev/}"
done

mount | grep -q "$DIRECTORY" || mount -r "$DIRECTORY" 2>"$TMP.err"
[ "$?" != "0" ] && { $DIALOG --cr-wrap --msgbox "$ERROR0 `cat $TMP.err`" 10 75; bailout; }
NTFS=""
mount | grep -q "$DIRECTORY.*ntfs"
[ "$?" = "0" ] && NTFS=true

IMAGE="$(ls -1d $DIRECTORY/[Kk][Nn][Oo][Pp][Pp][Ii][Xx].[Ss][Ww][Pp] 2>/dev/null)"

# Language-dependent Messages
case "$LANGUAGE" in
de*|at*|ch*)
MESSAGE6="Dieses Image ist gerade in Benutzung, daher kann es nicht gelscht werden! Bitte booten Sie ggf. Knoppix neu, OHNE das Image $IMAGE einzubinden."
;;
ko)
MESSAGE6="현재 사용중인 이미지입니다. 만약 이 이미지를 삭제/포맷 하고 싶다면, $IMAGE 이미지를 비활성화 한 상태에서 Knoppix를 재부팅 하십시오."
;;
*)
MESSAGE6="This image is currently in use. If you want to delete/reformat it, please reboot Knoppix first, without activating the image $IMAGE."
;;
esac

if [ -n "$IMAGE" -a -f "$IMAGE" ]; then
 { mount ; cat /proc/swaps; } | grep -q "$IMAGE" && { $DIALOG --cr-wrap --msgbox "$MESSAGE6" 10 75; bailout; }
 if iszero "$IMAGE"; then
  true
 else
  $DIALOG --cr-wrap --clear --defaultno --yesno "$MESSAGE7" 6 75 || bailout
 fi
else
 IMAGE=""
 [ -n "$NTFS" ] && { $DIALOG --cr-wrap --msgbox "$MESSAGE4" 10 75; bailout; }
fi

# Here, we have either NO image, or an existing image that is OK to overwrite.
# Now, make partition writable
mount -o remount,rw "$DIRECTORY" || { $DIALOG --cr-wrap --msgbox "$MESSAGE8" 10 75; bailout; }

# Language-dependent Messages
case "$LANGUAGE" in
de|at|ch)
MESSAGE2="Bitte geben Sie an, wieviel MB Sie als SWAP verwenden wollen. Empfohlen: 60 - 128. Frei: "
MESSAGE3="Erzeuge swapfile 'knoppix.swp' auf $DIRECTORY..."
ERROR1="Leider ist nicht genug Platz auf dieser Partition ($DIRECTORY), es sollten mindestens 60 MB frei sein."
SUCCESS="Das Einrichten des Swapfiles 'knoppix.swp' auf $DIRECTORY war erfolgreich."
;;
es)
MESSAGE2="Por favor, especifique la cantidad de espacio en disco que quiere utilizar como SWAP. Recomendado: 60 - 128. Libre: "
MESSAGE3="Creando archivo de memoria virtual 'knoppix.swp' en $DIRECTORY..."
ERROR1="Lo siento, no hay suficiente espacio libre en $DIRECTORY. Son necesarios al menos 60 MB."
SUCCESS="Archivo swap 'knoppix.swp' en $DIRECTORY creado satisfactoriamente."
;;
ko)
MESSAGE2="스왑으로 사용하기 원하는 디스크영역의 용량을 정해주십시요. 추천: 60-128. 사용가능:"
MESSAGE3="Creating swapfile 'knoppix.swp' on $DIRECTORY..."
ERROR1="$p에 공간이 충분하지 않습니다. 최소 60MB가 필요합니다."
SUCCESS="$p에 스왑파일 'knoppix.swp'가 성공적으로 생성되었습니다."
;;
*)
MESSAGE2="Please specify the amount of diskspace that you want to use as SWAP. Recommended: 60 - 128. Free: "
MESSAGE3="Creating swapfile 'knoppix.swp' on $DIRECTORY..."
ERROR1="Sorry, not enough free space on $DIRECTORY. At least 60 MB required."
SUCCESS="Swapfile 'knoppix.swp' on $DIRECTORY successfully created."
;;
esac

AVAIL="$(df -m $DIRECTORY | tail -1 | awk '{print $4}')"
if [ "$AVAIL" -lt 60 ]; then
$DIALOG --msgbox "$ERROR1" 10 45
umount -r $DIRECTORY
else
rm -f "$TMP"
$DIALOG --inputbox "$MESSAGE2 $AVAIL" 8 62 "60" 2>"$TMP" || { umount "$DIRECTORY" ; bailout; }
IN="`cat $TMP`" 
[ "$IN" -ge 60 -a "$IN" -le "$AVAIL" ] 2>/dev/null || IN="60"
echo "$MESSAGE3"
LOOPDEV="$(findfreeloop)" || bailout
if [ -f "$IMAGE" ]; then
losetup "$LOOPDEV" "$IMAGE" || bailout
else
IMAGE="$DIRECTORY/knoppix.swp"
dd if=/dev/zero of="$IMAGE" bs=1000k count="$IN" && \
losetup "$LOOPDEV" "$IMAGE" || bailout
fi
mkswap -v1 "$LOOPDEV"
losetup -d "$LOOPDEV"
swapon -v "$IMAGE" 2>/dev/null && \
echo "$f swap swap defaults 0 0" >>/etc/fstab
umount -r "$DIRECTORY"
[ "$?" = "0" ] && { sleep 2 ; $DIALOG --msgbox "$SUCCESS" 10 45; } || umount "$d" 2>/dev/null
fi

bailout
